\documentclass[12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fullpage}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{array}
\usepackage{color}
\usepackage{placeins}
\usepackage{graphicx}
\usepackage{float}
\usepackage[hidelinks]{hyperref}
\usepackage{listings}
\usepackage[margin=2cm]{geometry}
\usepackage{setspace}
\usepackage{natbib}
\usepackage{proof}
\usepackage{multirow}
\usepackage{hhline}
\usepackage{wrapfig}
\usepackage [english]{babel}
\usepackage{grffile}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage[tikz]{bclogo}
\usetikzlibrary{chains}
\usetikzlibrary{positioning}
\usetikzlibrary{arrows}
\usepackage{lscape}
\usepackage [autostyle, english = american]{csquotes}
\usepackage{enumitem}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{indentfirst}
\usepackage{hyperref}
\usepackage{pdfpages}
\usepackage{booktabs}
\usepackage{pgfgantt}
\newcommand{\tabitem}{~~\llap{\textbullet}~~}
\bibliographystyle{apsr}
\bibpunct{(}{)}{;}{a}{,}{,}
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\setlength{\tabcolsep}{.18cm}
\usepackage{fancyvrb}
\usepackage{etoc}
\usepackage{sectsty}
\sectionfont{\fontsize{14}{14}\selectfont}
\subsectionfont{\fontsize{12}{12}\selectfont}

% ==Cross Referencing Different Docs
\usepackage{xr}
\externaldocument{AfricaCup_Paper_Final}

\usepackage{titlesec}

\makeatletter
\@addtoreset{section}{part}
\@addtoreset{figure}{part}
\@addtoreset{table}{part}
\makeatother
\titleformat{\part}[display]
{\normalfont\LARGE\bfseries}{}{0pt}{}

\makeatletter
\renewcommand{\l@section}{\@dottedtocline{1}{1.5em}{2.6em}}
\renewcommand{\l@subsection}{\@dottedtocline{2}{4.0em}{3.6em}}
\renewcommand{\l@subsubsection}{\@dottedtocline{3}{7.4em}{4.5em}}
\makeatother

% === new commands ===
\newcommand\ud{\mathrm{d}}
\newcommand\dist{\buildrel\rm d\over\sim}
\newcommand\ind{\stackrel{\rm indep.}{\sim}}
\newcommand\iid{\stackrel{\rm i.i.d.}{\sim}}
\newcommand\logit{{\rm logit}}
\renewcommand\r{\right}
\renewcommand\l{\left}
\newcommand\Var{{\rm Var}}
\newcommand\var{{\rm var}}
\newcommand\Cov{{\rm Cov}}
\newcommand\E{\mathbb{E}}
\newcommand\V{\mathbb{V}}
\newcommand\cN{\mathcal{N}}
\newcommand\cS{\mathcal{S}}
\newcommand\cX{\mathcal{X}}
\newcommand\wX{\widetilde{X}}
\newcommand{\diag}{\mathop{\mathrm{diag}}}
\newcommand{\argmax}{\operatornamewithlimits{argmax}}
\newcommand{\argmin}{\operatornamewithlimits{argmin}}
\newcommand{\indep}{\mbox{$\perp\!\!\!\perp$}}
\def\independenT#1#2{\mathrel{\rlap{$#1#2$}\mkern2mu{#1#2}}}
\DeclareMathOperator{\sgn}{sgn}
\providecommand{\norm}[1]{\lVert#1\rVert}

\def\changemargin#1#2{\list{}{\rightmargin#2\leftmargin#1}\item[]}
\let\endchangemargin=\endlist 

\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{P}[1]{>{\raggedright\tabularxbackslash}p{#1}}

\newcounter{myWeekNum} %for gantt
\stepcounter{myWeekNum}
%
\newcommand{\myWeek}{\themyWeekNum
    \stepcounter{myWeekNum}
    \ifnum\themyWeekNum=53
         \setcounter{myWeekNum}{1}
    \else\fi
}

\newenvironment{bluetext}{\color{blue}}{\ignorespacesafterend}

\begin{document}

<<eval=TRUE, echo=FALSE, results='hide', message=FALSE>>= 

require(knitr, quietly = TRUE)

opts_chunk$set(cache = TRUE, 
               cache.path = 'cache_SI/',
               fig.path = 'figures_SI/', 
               tidy = TRUE, 
               echo = FALSE, 
               warning = FALSE, 
               message = FALSE, 
               fig.pos = 'H',
               dev = 'pdf', 
               dpi=200)

options(width = 110, digits = 2)

knit_hooks$set(inline = function(x) {
  prettyNum(x, big.mark=",")
})

@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

<<eval=TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, error=FALSE, message=FALSE>>=

### load data
load("data/ACUP_anonymized_final.RData")  

### load packages and functions
library(estimatr, quietly = TRUE)
library(foreign, quietly = TRUE)
library(tidyverse, quietly = TRUE)
library(reshape2, quietly = TRUE)
library(gtools, quietly = TRUE)
library(patchwork, quietly = TRUE)
library(kableExtra, quietly = TRUE)
library(stargazer, quietly = TRUE)
library(CBPS, quietly = TRUE)
library(sp, quietly = TRUE) 
library(rgdal, quietly = TRUE)
library(maps, quietly = TRUE)
library(mapdata, quietly = TRUE)
library(maptools, quietly = TRUE)
library(gpclib, quietly = TRUE)
library(ggmap, quietly = TRUE)
library(doMC, quietly = TRUE)
library(texreg, quietly = TRUE)
library(haven, quietly = TRUE)

### Bring in GIS shape files
KYcounties.shp <- rgdal::readOGR("data/ken_admbnda_adm1_iebc_20180607.shp", verbose = FALSE)
KYcounties.df <- slot(KYcounties.shp, "data")

TZregions.shp <- rgdal::readOGR("data/tza_admbnda_adm1_20181019.shp", verbose = FALSE)
TZregions.df <- slot(TZregions.shp, "data")

geokey <- read.csv("data/ACUP_geokey.csv", header = TRUE)


## Main function to run regression analyses
run_mods <- function(data, ctrl_formula = ~Win + 
                       female + 
                       age_numb2 + 
                       edu + 
                       urban + 
                       livedout + 
                       ref_know + 
                       job + 
                       hh_wealth + 
                       voted_last2 + 
                       polclose + 
                       religion2 + 
                       religiosity +
                       UserLanguage_b + 
                       Period){
  
  ## Get covariates
  cov_terms <- terms(ctrl_formula)
  
  ## Analysis
  est_df <- data %>% dplyr::select(labels(cov_terms), 
                  MatchInfo,
                  Diversity,
                  PanAfrica,
                  SurvPrime,
                  starts_with("idcircle_"),
                  starts_with("nateth"),
                  starts_with("natpride"),
                  starts_with("ethpride"),
                  starts_with("afrpride"),
                  starts_with("affective_1"),
                  starts_with("affective_2"),
                  starts_with("behavioral_1"),
                  starts_with("behavioral_2"),
                  starts_with("cognitive_1"),
                  starts_with("cognitive_2"),
                  starts_with("affective_std"),
                  starts_with("behavioral_std"),
                  starts_with("cognitive_std"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"),
                  starts_with("ref_disease_recode"),
                  starts_with("ref_econ"),
                  starts_with("ref_post"),
                  starts_with("nat_govspend_")
                  ) %>%
    dplyr::select(-contains("_DO_")) %>%
    mutate(respid = 1:n()) %>%
    gather(key = response, value = value, 
           -c(labels(cov_terms), MatchInfo, Diversity, PanAfrica, SurvPrime,
              respid)) %>% 
    mutate(time = case_when(str_ends(response, "_b")~"Baseline",
                            str_ends(response, "_e")~"Endline",
                            TRUE~"ruh-roh"),
           response = str_sub(response, 1, -3)) %>%
    group_by(response) %>%
    do({
      
      ## Marginalize over primes
      mod_base <- try(lm_robust(update(value ~ Win*time, reformulate(c(".",labels(cov_terms)))),
                           data = ., clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>%
        filter(grepl("Win:timeEndline", term))
      
      ## Additional effect of each prime
      mod_inter <- try(lm_robust(update(value ~ MatchInfo*time*Win + 
                                          Diversity*time*Win + PanAfrica*time*Win, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>%
        filter(str_count(term, ":") == 2)
      
      ## Additional effect of any prime
      mod_anyprime <-  try(lm_robust(update(value ~ SurvPrime*time*Win, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>% 
        filter(term == "SurvPrime:timeEndline:Win")
      
      ## Clean and output
      bind_rows(mod_base, mod_inter, mod_anyprime) %>%
        mutate(term = case_when(grepl("MatchInfo", term)~"MatchInfo x Win",
                                grepl("Diversity", term)~"Diversity x Win",
                                grepl("PanAfrica", term)~"PanAfrica x Win",
                                grepl("SurvPrime", term)~"Any Prime x Win",
                                TRUE~"Win"),
               term = fct_relevel(term, "Win"))
    }) 
  
  return(est_df)  
  
}

## ggplot theme
yy_theme <- function(){
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11),
          legend.position = 'none',
          axis.text.x  = element_text(angle=0, vjust=1, hjust = 0, size=11))
  }

@

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\title{Team and Nation: Sports, Nationalism,\\ and Attitudes toward Refugees
\\ {\large Supplementary Information for Online Publication}\footnote{All replication material, including {\tt R} code and data, are available via Harvard University's Dataverse: DOI: \href{https://doi.org/10.7910/DVN/XCSB9W}{10.7910/DVN/XCSB9W} \citep{DVN/XCSB9W_2021}.} 
}

\author{Leah Rosenzweig\thanks{Postdoctoral Fellow, Stanford University. E-mail: \href{lrosenzw@stanford.edu}{lrosenzw@stanford.edu}} 
~and Yang-Yang Zhou\thanks{Assistant Professor, Department of Political Science, University of British Columbia. E-mail: \href{yangyang.zhou@ubc.ca}{yangyang.zhou@ubc.ca}}
\thanks{Authors contributed equally. Author order randomized using \url{https://randomizeauthor.shinyapps.io/shiny}.}
}

\date{\today}

%%%%%%%%%%%%%%%%% END OF PREAMBLE %%%%%%%%%%%%%%%%
\renewcommand{\harvardurl}{URL: \url}

\maketitle


%To number supplemental material with 'S': 
\renewcommand{\thesection}{S\arabic{section}}   
\renewcommand{\thetable}{S\arabic{table}}   
\renewcommand{\thefigure}{S\arabic{figure}}
\renewcommand{\theequation}{S\arabic{equation}}


\newpage
\part{\large{Supplementary Information}}
\vspace{-.5cm}
\addtocontents{toc}{\protect\setcounter{tocdepth}{2}}
\tableofcontents

\setstretch{1.3}


%%% DESCRIPTIVES
\newpage
\section{Descriptive Statistics and Figures}
\label{sec:SIdescript}

\subsection{Respondent Summary Statistics}

This section summarizes respondent demographics and covariate balance. 

% Sum stat tables
<<Sumstats, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

descriptlabels <-  c("Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion", 
                       "Religiosity")

ACUPdescript <- subset(ACUP, select = c("female", 
                       "age_numb2",
                       "edu",
                       "urban", 
                       "livedout", 
                       "ref_know", 
                       "job",
                       "hh_wealth", 
                       "voted_last2",
                       "polclose",
                       "religion", 
                       "religiosity"))

stargazer(ACUPdescript,
          title = "Descriptive statistics of all study respondents",
          median = TRUE,
          digits=2, 
          digits.extra=2,
          covariate.labels = descriptlabels,
          font.size = "small",
          label = "tab:sumstats")

@

<<Sumstats_KY, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

descriptlabels <-  c("Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion", 
                       "Religiosity")

ACUPdescript <- subset(ACUP[ACUP$country == "Kenya",], select = c("female", 
                       "age_numb2",
                       "edu",
                       "urban", 
                       "livedout", 
                       "ref_know", 
                       "job",
                       "hh_wealth", 
                       "voted_last2",
                       "polclose",
                       "religion", 
                       "religiosity"))

stargazer(ACUPdescript,
          title = "Descriptive statistics of Kenyan study respondents",
          median = TRUE,
          digits=2, 
          digits.extra=2,
          covariate.labels = descriptlabels,
          font.size = "small",
          label = "tab:sumstats_ky")

@

<<Sumstats_TZ, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

descriptlabels <-  c("Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion", 
                       "Religiosity")

ACUPdescript <- subset(ACUP[ACUP$country == "Tanzania",], select = c("female", 
                       "age_numb2",
                       "edu",
                       "urban", 
                       "livedout", 
                       "ref_know", 
                       "job",
                       "hh_wealth", 
                       "voted_last2",
                       "polclose",
                       "religion", 
                       "religiosity"))

stargazer(ACUPdescript,
          title = "Descriptive statistics of Tanzanian study respondents",
          median = TRUE,
          digits=2, 
          digits.extra=2,
          covariate.labels = descriptlabels,
          font.size = "small",
          label = "tab:sumstats_tz")

@


% Maps and covar figs
<<Maps, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="These maps show the regions where our respondents are from. As expected, most are from the capitals/largest urban areas of Nairobi and Dar es Salaam (darkest regions).">>=

## ---------------
## Kenya Map
## ---------------

# Fortify 
KYcounties.shp@data$id <- rownames(KYcounties.shp@data)
KYcounties_points <- fortify(KYcounties.shp, region="id")
KYcounties.df <- plyr::join(KYcounties_points, KYcounties.shp@data, by="id")
KYcounties.df$ADM1_EN <- as.character(KYcounties.df$ADM1_EN)

# Respondent count
# step that joins region number to region name
geokey_ky <- geokey[,c("Kenya_county", "Kenya_key")] %>%
  rename(region = Kenya_key, county = Kenya_county)
ky_resp_count <- ACUP[ACUP$country == "Kenya",] %>% 
  group_by(region) %>%
  summarize(n_resp = n()) %>%
  left_join(geokey_ky) %>%
  mutate(county = sub("\\s+[^ ]+$", "", county))
ky_resp_count$region <- ky_resp_count$county

ky_resp_count$region <- as.character(ky_resp_count$region)
ky_resp_count$region[ky_resp_count$region == "Taita–Taveta"] <- "Taita Taveta"
ky_resp_count$region[ky_resp_count$region == "Trans-Nzoia"] <- "Trans Nzoia"

KYcounties.df <- left_join(KYcounties.df, ky_resp_count, by = c("ADM1_EN" = "region"))
  
# Map
KY.map <- ggplot(KYcounties.df) +
    geom_polygon(aes(fill = n_resp, x = long, 
                     y = lat, group = group), 
                 data = KYcounties.df,
                 color = "black",
                 size = 0.2) +
  ggtitle("Kenya") +
  scale_fill_gradient("Number of\nrespondents", low = "white", high = "black",
  space = "Lab", na.value = "white", guide = "colourbar",
  aesthetics = "fill") +
    theme(axis.line=element_blank(),
          axis.text.x=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),
          panel.background=element_blank(),
          panel.border=element_rect(colour = "white", fill=NA, size=.6),
          panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),
          plot.background=element_blank()) +
          coord_fixed(1) 

## ---------------
## Tanzania Map
## ---------------

# Fortify 
TZregions.shp@data$id <- rownames(TZregions.shp@data)
TZregions_points <- fortify(TZregions.shp, region="id")
TZregions.df <- plyr::join(TZregions_points, TZregions.shp@data, by="id")

# Respondent count
geokey_tz <- geokey[,c("Tanzania_region", "Tanzania_key")] %>%
  rename(region = Tanzania_key, county = Tanzania_region) %>% drop_na()
TZ_resp_count <- ACUP[ACUP$country == "Tanzania",] %>% 
  group_by(region) %>%
  summarize(n_resp = n()) %>%
  left_join(geokey_tz) %>%
  mutate(county = sub("\\s+[^ ]+$", "", county))
TZ_resp_count$region <- TZ_resp_count$county

TZ_resp_count$region <- as.character(TZ_resp_count$region)
TZ_resp_count$region[TZ_resp_count$region == "Dar es Salaam"] <- "Dar-es-salaam"
TZ_resp_count$region[TZ_resp_count$region == "Coast"] <- "Kusini Pemba"
TZ_resp_count$region[TZ_resp_count$region == "Zanzibar"] <- "Kusini Unguja"

TZregions.df <- left_join(TZregions.df, TZ_resp_count, by = c("ADM1_EN" = "region"))
  
# Map
TZ.map <- ggplot(TZregions.df) +
    geom_polygon(aes(fill = n_resp, x = long, 
                     y = lat, group = group), 
                 data = TZregions.df,
                 color = "black",
                 size = 0.2) +
  scale_fill_gradient("Number of\nrespondents", low = "white", high = "black",
  space = "Lab", na.value = "white", guide = "colourbar",
  aesthetics = "fill") +
  ggtitle("Tanzania") +
    theme(axis.line=element_blank(),
          axis.text.x=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),
          panel.background=element_blank(),
          panel.border=element_rect(colour = "white", fill=NA, size=.6),
          panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),
          plot.background=element_blank()) +
          coord_fixed(1) 

# Plot side by side
KY.map + TZ.map

@

<<Covars, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 14, fig.height = 19, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="These plots show the distributions of respondent demographics by country.">>=

### Age
KY.age <- ggplot(ACUP_ky, aes(x= age_numb2)) + 
  geom_histogram(aes(y=..density..),      
                 binwidth=2,
                 colour="gray70", fill="white") +
  geom_density(alpha=.2, fill="gray") +
  geom_vline(data=ACUP_ky, aes(xintercept=mean(ACUP_ky$age_numb2, 
                          na.rm = T)), linetype="dashed", size=1) +
  geom_vline(data=ACUP_ky, aes(xintercept=median(ACUP_ky$age_numb2, na.rm = T)),
             linetype="dotted", size=1) +
  geom_text(data = ACUP_ky, aes(label = 
        paste("mean =", as.character(round(mean(ACUP_ky$age_numb2, na.rm = T), 2))), 
        x = 50, y = .04),  size=3.5) +
  geom_text(data = ACUP_ky, aes(label = 
        paste("median =", as.character(round(median(ACUP_ky$age_numb2, na.rm = T), 2))), 
        x = 50, y = .045),  size=3.5) +
  xlab("Age") +
  ylab("Proportion") +
  xlim(15, 60) +
  ggtitle("Kenya Age") +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = c(0.05, 0.9))

TZ.age <- ggplot(ACUP_tz, aes(x= age_numb2)) + 
  geom_histogram(aes(y=..density..),      
                 binwidth=2,
                 colour="gray70", fill="white") +
  geom_density(alpha=.2, fill="gray") +
  geom_vline(data=ACUP_tz, aes(xintercept=mean(ACUP_tz$age_numb2, 
                          na.rm = T)), linetype="dashed", size=1) +
  geom_vline(data=ACUP_tz, aes(xintercept=median(ACUP_tz$age_numb2, na.rm = T)),
             linetype="dotted", size=1) +
  geom_text(data = ACUP_tz, aes(label = 
        paste("mean =", as.character(round(mean(ACUP_tz$age_numb2, na.rm = T), 2))), 
        x = 50, y = .04),  size=3.5) +
  geom_text(data = ACUP_tz, aes(label = 
        paste("median =", as.character(round(median(ACUP_tz$age_numb2, na.rm = T), 2))), 
        x = 50, y = .045),  size=3.5) +
  xlab("Age") +
  ylab("Proportion") +
  xlim(15, 60) +
  ggtitle("Tanzania Age") +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = c(0.05, 0.9))

### Gender
ky_resp_count <- ACUP_ky %>% 
  group_by(female) %>%
  summarize(n_resp = n(),
            country = "Kenya")

tz_resp_count <- ACUP_tz %>% 
  group_by(female) %>%
  summarize(n_resp = n(),
            country = "Tanzania")

Gender <- bind_rows(ky_resp_count[1:2,], tz_resp_count[1:2,]) %>%
  group_by(country) %>%
  mutate(female = case_when(female == 1~"Female", TRUE~"Male"),
         prop_resp = n_resp / sum(n_resp)) %>%
  ggplot(aes(female, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Gender", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = c(0.15, 0.85))

### Edu level
ky_resp_count <- ACUP_ky %>% 
  group_by(edu) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(edu) %>%
  summarize(n_resp = n(),
            country = "TZ")

Edu <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
  mutate(edu = case_when(edu == 1~"No schooling", 
                         edu == 2~"Some primary school",
                         edu == 3~"Completed primary school",
                         edu == 4~"Some secondary school",
                         edu == 5~"Completed secondary school",
                         edu == 6~"Some post-secondary school",
                         edu == 7~"Diploma course/certificate",
                         edu == 8~"University degree", TRUE~NA_character_),
         edu = fct_relevel(edu, "No schooling", 
                           "Some primary school",
                           "Completed primary school",
                           "Some secondary school",
                           "Completed secondary school",
                           "Some post-secondary school",
                           "Diploma course/certificate",
                           "University degree"),
           prop_resp = n_resp / sum(n_resp)) %>% 
  drop_na() %>%
  ggplot(aes(edu, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Education", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Urban
ky_resp_count <- ACUP_ky %>% 
  group_by(urban) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(urban) %>%
  summarize(n_resp = n(),
            country = "TZ")

Urban <- bind_rows(ky_resp_count[1:2,], tz_resp_count[1:2,]) %>%
  group_by(country) %>%
  mutate(urban = case_when(urban == 1~"Urban", TRUE~"Rural"),
         prop_resp = n_resp / sum(n_resp)) %>% 
  ggplot(aes(urban, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Urban", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Lived Out
ky_resp_count <- ACUP_ky %>% 
  group_by(livedout) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(livedout) %>%
  summarize(n_resp = n(),
            country = "TZ")

LivedOut <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
  mutate(livedout = case_when(livedout == 0~"Never", 
                         livedout == 1~"Less than 1 year",
                         livedout == 2~"1-5 years",
                         livedout == 3~"5-10 years",
                         livedout == 4~"More than 10 years", TRUE~NA_character_),
         livedout = fct_relevel(livedout, "Never", 
                           "Less than 1 year",
                           "1-5 years",
                           "5-10 years",
                           "More than 10 years"),
          prop_resp = n_resp / sum(n_resp)) %>% 
  drop_na() %>%
  ggplot(aes(livedout, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Lived Outside of Country", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  #ylim(0,1300) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')


### Knows Refugee
ky_resp_count <- ACUP_ky %>% 
  group_by(ref_know) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(ref_know) %>%
  summarize(n_resp = n(),
            country = "TZ")

Ref_Know <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
  mutate(ref_know = case_when(ref_know == 1~"Yes", TRUE~"No"),
          prop_resp = n_resp / sum(n_resp)) %>%
  ggplot(aes(ref_know, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Knows any Refugees", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  #ylim(0,1000) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Employment
ky_resp_count <- ACUP_ky %>% 
  group_by(job) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(job) %>%
  summarize(n_resp = n(),
            country = "TZ")

Employment <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
    mutate(job = case_when(job == 0~"No-not looking", 
                         job == 1~"No-looking",
                         job == 2~"Yes-part time",
                         job == 3~"Yes-full time",TRUE~NA_character_),
         job = fct_relevel(job, "No-not looking",
                           "No-looking",
                           "Yes-part time",
                           "Yes-full time"),
         prop_resp = n_resp / sum(n_resp)) %>%
  drop_na() %>%
  ggplot(aes(job, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Employment Status", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### HH Wealth
ky_resp_count <- ACUP_ky %>% 
  group_by(hh_wealth) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(hh_wealth) %>%
  summarize(n_resp = n(),
            country = "TZ")

HHWealth <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
  mutate(prop_resp = n_resp / sum(n_resp)) %>%
  ggplot(aes(hh_wealth, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Household Wealth - Number of Items", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  #scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Voted in Last Election
ky_resp_count <- ACUP_ky %>% 
  group_by(voted_last) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(voted_last) %>%
  summarize(n_resp = n(),
            country = "TZ")

Voted_Last <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
   mutate(voted_last = case_when(voted_last == 1~"I voted", 
                         voted_last == 2~"I decided not to vote",
                         voted_last == 3~"I was unable to vote", TRUE~NA_character_),
         voted_last = fct_relevel(voted_last, "I voted", 
                           "I decided not to vote",
                           "I was unable to vote"),
         prop_resp = n_resp / sum(n_resp)) %>%
  drop_na() %>%
  ggplot(aes(voted_last, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Voted in Last Election", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Close to a Political Party
ky_resp_count <- ACUP_ky %>% 
  group_by(polclose) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(polclose) %>%
  summarize(n_resp = n(),
            country = "TZ")

Pol_Close <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
  mutate(polclose = case_when(polclose == 0~"No", TRUE~"Yes"),
         prop_resp = n_resp / sum(n_resp)) %>%
  ggplot(aes(polclose, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Close to a Political Party", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Religion
ky_resp_count <- ACUP_ky %>% 
  group_by(religion) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(religion) %>%
  summarize(n_resp = n(),
            country = "TZ")

Religion <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
   mutate(religion = case_when(religion == 1~"Christian", 
                         religion == 2~"Muslim",
                         religion == 3~"Hindu", 
                         religion == 4~"Animist/Traditional", 
                         religion == 5~"Other", 
                         religion == 6~"None", 
                         TRUE~NA_character_),
         religion = fct_relevel(religion, "Christian", 
                                  "Muslim",
                                  "Hindu", 
                                  "Animist/Traditional", 
                                  "Other", 
                                  "None"),
          prop_resp = n_resp / sum(n_resp)) %>%
  drop_na() %>%
  ggplot(aes(religion, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Religion", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')

### Reliosity
ky_resp_count <- ACUP_ky %>% 
  group_by(religiosity) %>%
  summarize(n_resp = n(),
            country = "KY")

tz_resp_count <- ACUP_tz %>% 
  group_by(religiosity) %>%
  summarize(n_resp = n(),
            country = "TZ")

Religiosity <- bind_rows(ky_resp_count, tz_resp_count) %>%
  group_by(country) %>%
   mutate(religiosity = case_when(religiosity == 0~"Never", 
                         religiosity == 1~"Few times a year", 
                         religiosity == 2~"Once a month",
                         religiosity == 3~"Once a week", 
                         religiosity == 4~"Few times a week", 
                         religiosity == 5~"Once a day", 
                         religiosity == 6~"Multiple times a day", 
                         TRUE~NA_character_),
         religiosity = fct_relevel(religiosity, "Never", 
                                 "Few times a year", 
                                 "Once a month",
                                 "Once a week", 
                                 "Few times a week", 
                                 "Once a day", "Multiple times a day"),
         prop_resp = n_resp / sum(n_resp)) %>%
  drop_na() %>%
  ggplot(aes(religiosity, prop_resp, 
             group = country, fill = country)) + 
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "Religiosity - Frequency in Engaging in Practices", y = "Proportion of Respondents") +
  scale_fill_manual(values=c("gray40", "gray70")) +
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11), 
          legend.position = 'none')


# plot
(KY.age + TZ.age) /
(Gender + Urban + Ref_Know) /
(Edu + LivedOut) /
(Employment + HHWealth + Voted_Last) /
(Pol_Close + Religion + Religiosity + plot_layout(widths = c(1, 1, 2)))

@


\subsection{Covariate Balance}

<<Balance1, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 8, fig.height = 4, fig.align='center', out.width= ".8\\linewidth", warning=FALSE, message=FALSE, fig.cap="This plot shows covariate imbalance across country.">>=

baltest_out <- ACUP %>% filter(doublerand == 0) %>%
  mutate(christian = case_when(religion2 == "christian"~1, TRUE~0),
         muslim = case_when(religion2 == "muslim"~1, TRUE~0),
         en_lan = case_when(UserLanguage_b == "EN"~1, TRUE~0),
         sw_lan = case_when(UserLanguage_b == "SW"~1, TRUE~0),
         country = fct_relevel(country, "Kenya")) %>%
  dplyr::select(country, female, age_numb2, edu, urban, livedout, ref_know, job, hh_wealth,
         voted_last2, polclose, christian, muslim, en_lan, sw_lan) %>%
  gather(key = var, value = outcome, -country) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ country, data = .), silent = TRUE)
    data.frame(pval = t_out$p.value, 
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2])
  })

## Run KS test against uniform
ks_out <- data.frame(pval = ks.test(baltest_out$pval, "punif")$p.value) %>%
  mutate(pval = as.numeric(pval),
         text = paste0("KS Test P-value vs. Uniform: ", round(pval, 3)))

## Plot statistic
ggplot(baltest_out, aes(sample = pval)) + 
  stat_qq(distribution = stats::qunif) + 
  geom_text(data = ks_out, aes(x = .15, y = .95, label = text)) + 
  labs(x = "Theoretical Quantile", y = "Empirical Quantile") +
  yy_theme() +
  geom_abline(aes(intercept = 0, slope = 1), lty = "dashed")

## Report balance statistics
baltest_out %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, pval) %>%
  rename(`Kenya Mean` = mean_group1, `TZ Mean` = mean_group2) %>%
  mutate(`Kenya Mean` = round(`Kenya Mean`, 3),
         `TZ Mean` = round(`TZ Mean`, 3),
         pval = round(pval, 3)) %>%
  kable() %>%
  kable_styling(bootstrap_options = "striped")

@

From Figure \ref{fig:Balance1}, respondents are not balanced across the two countries in terms of their covariates. Of our respondents, compared to Tanzanians, Kenyans are slightly younger, Christian, more likely to use English as their main language, less likely to have a job, be female, less political, more likely to know a refugee, less urban, and more likely to have voted in the last election. Respondents across countries are balanced on education. 

<<Balance2, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 8, fig.height = 4, fig.align='center', out.width= ".8\\linewidth", warning=FALSE, message=FALSE, fig.cap="This plot shows covariate balance across survey treatment">>=

baltest_out <- ACUP %>% filter(doublerand == 0) %>%
  mutate(christian = case_when(religion2 == "christian"~1, TRUE~0),
         muslim = case_when(religion2 == "muslim"~1, TRUE~0),
         en_lan = case_when(UserLanguage_b == "EN"~1, TRUE~0),
         sw_lan = case_when(UserLanguage_b == "SW"~1, TRUE~0)) %>%
  dplyr::select(SurvPrime, female, age_numb2, edu, urban, livedout, ref_know, job, hh_wealth,
         voted_last2, polclose, christian, muslim, en_lan, sw_lan) %>%
  gather(key = var, value = outcome, -SurvPrime) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ SurvPrime, data = .), silent = TRUE)
    data.frame(pval = t_out$p.value, 
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2])
  })

## Run KS test against uniform
ks_out <- data.frame(pval = ks.test(baltest_out$pval, "punif")$p.value) %>%
  mutate(pval = as.numeric(pval),
         text = paste0("KS Test P-value vs. Uniform: ", round(pval, 3)))

## Plot statistic
ggplot(baltest_out, aes(sample = pval)) + 
  stat_qq(distribution = stats::qunif) + 
  geom_text(data = ks_out, aes(x = .2, y = .95, label = text)) + 
  labs(x = "Theoretical Quantile", y = "Empirical Quantile") +
  yy_theme() +
  geom_abline(aes(intercept = 0, slope = 1), lty = "dashed")

## Report balance statistics
baltest_out %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, pval) %>%
  rename(`No Prime Mean` = mean_group1, `Primed Mean` = mean_group2) %>%
  mutate(`No Prime Mean` = round(`No Prime Mean`, 3),
         `Primed Mean` = round(`Primed Mean`, 3),
         pval = round(pval, 3)) %>%
  kable() %>%
  kable_styling(bootstrap_options = "striped")

@

From Figure \ref{fig:Balance2}, respondents are balanced across survey control and prime conditions, which is unsurprising since we randomized survey treatment.  


\subsection{Our Facebook sample compared to Afrobarometer}
\label{subsec:samplevsAB}

The following tables compare our sample to the nationally representative Afrobarometer survey (round 7) in each country. The first two tables illustrate that our sample is younger, slightly more Christian, much more likely to have completed secondary school, less employed, less female, wealthier, less likely to say they identify with their national identity compared to their ethnicity, slightly more urban, and less likely to say they voted in Tanzania but slightly more likely to say they voted in Kenya.

<<KY_AB_1, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

# redefine edu, religion
ACUP$edu_sec.ab <- ifelse(ACUP$edu >=5,1,0)
ACUP$christian.ab <- ifelse(ACUP$religion==1,1,0)
ACUP$employed.ab <- ifelse(ACUP$job>=2,1,0)
ACUP$wealth.ab <- rowSums(ACUP[,c("hh_own_1","hh_own_2","hh_own_3","hh_own_4","hh_own_5","hh_own_6")],na.rm=T) # sum hh_own Q's 1-6 (AB doesnt ask about bicycle)
  
# kenya sample v. AB
descriptlabels <-  c("Female", 
                       "Age",
                       "Completed Secondary School",
                       "Urban", 
                       "Voted",
                       "Christian",
                       "Employed",
                       "Household Wealth", 
                       "National vs. Ethnic ID",
                       "Country")

ACUPdescript <- ACUP %>% 
                dplyr::select(female, 
                       age_numb2,
                       edu_sec.ab,
                       urban,
                       voted_last2,
                       christian.ab,
                       employed.ab,
                       wealth.ab,
                       nateth_b,
                       country)

names(ACUPdescript) <- descriptlabels

ACUPdescript$data <- "Facebook sample"

# clean afrobarometer data for kenya and tanzania read in above
names(ab)[1:length(descriptlabels)-1] <- descriptlabels[1:length(descriptlabels)-1]


# merge AB + sample data
ab.fb <- smartbind(ACUPdescript,ab)

## KENYA TABLE ##
# full ab dataset
baltest_out_KY <- ab.fb %>% filter(Country == "Kenya") %>%
  dplyr::select(-fbnews) %>%
  gather(key = var, value = outcome, -Country,-data) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ data, data = .), silent = TRUE)
    data.frame(
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2],
               diff_means = t_out$estimate[2]-t_out$estimate[1],
               pvalue = t_out$p.value)
  })

## Report balance statistics
baltest_out_KY %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, diff_means) %>%
  rename(`Variable` = var, `Afrobarometer Mean` = mean_group1, `Sample Mean` = mean_group2, `Diff. in Means` = diff_means) %>%
  kable(align = "lccc",
        caption = "Comparing Afrobarometer and our sample in Kenya",
        label ="tab:abky") %>%
  kable_styling(bootstrap_options = "striped")

@

<<TZ_AB, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

## Tanzania TABLE ##
# full ab dataset
baltest_out_TZ <- ab.fb %>% filter(Country == "Tanzania") %>%
  dplyr::select(-fbnews) %>%
  gather(key = var, value = outcome, -Country,-data) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ data, data = .), silent = TRUE)
    data.frame(
               mean_group1 = t_out$estimate[1], 
               mean_group2 = t_out$estimate[2],
               diff_means = t_out$estimate[2]-t_out$estimate[1],
               pvalue = t_out$p.value)
  })

## Report balance statistics
baltest_out_TZ %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, diff_means) %>%
  rename(`Variable` = var, `Afrobarometer Mean` = mean_group1, `Sample Mean` = mean_group2, `Diff. in Means` = diff_means) %>%
  kable(align = "lccc",
        caption = "Comparing Afrobarometer and our sample in Tanzania",
        label ="tab:abTZ") %>%
  kable_styling(bootstrap_options = "striped")

@

The next two tables compare our sample to the subset of Afrobarometer respondents who said that they get news from social media, such as Facebook or Twitter. In Kenya, 30\% of Afrobarometer respondents say they get news from social media. In Tanzania, 20\% of Afrobarometer respondents say they get news from social media. When we subset to social media users in Afrobarometer we observe smaller differences between this subset and our sample with respect to age, secondary school completion, and percent female. 

<<KY_AB_2, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

# table comparing means btw sample and AB respondents who get news on FB
# ab dataset restricted to FB users :
baltest_out_KY_sub <- ab.fb %>% filter(Country == "Kenya", fbnews %in% c(NA,1)) %>%
  dplyr::select(-fbnews) %>%
  gather(key = var, value = outcome, -Country,-data) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ data, data = .), silent = TRUE)
    data.frame(
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2],
               diff_means = t_out$estimate[2]-t_out$estimate[1],
               pvalue = t_out$p.value)
  })

## Report balance statistics
baltest_out_KY_sub %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, diff_means) %>%
  rename(`Variable` = var, `Afrobarometer Mean` = mean_group1, `Sample Mean` = mean_group2, `Diff in Means` = diff_means) %>%
  kable(align = "lccc",
        caption = "Comparing Afrobarometer respondents who use social media and our sample in Kenya", 
        label = "tab:abky_sub") %>%
  kable_styling(bootstrap_options = "striped")
@

<<TZ_AB_2, eval = TRUE, echo=FALSE, fig.align='center', warning=FALSE, message=FALSE, strip.white=TRUE, results='asis'>>=

# table comparing means btw sample and AB respondents who get news on FB
# ab dataset restricted to FB users :
baltest_out_TZ_sub <- ab.fb %>% filter(Country == "Tanzania", fbnews %in% c(NA,1)) %>%
  dplyr::select(-fbnews) %>%
  gather(key = var, value = outcome, -Country,-data) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ data, data = .), silent = TRUE)
    data.frame(
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2],
               diff_means = t_out$estimate[2]-t_out$estimate[1],
               pvalue = t_out$p.value)
  })

## Report balance statistics
baltest_out_TZ_sub %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, diff_means) %>%
  rename(`Variable` = var, `Afrobarometer Mean` = mean_group1, `Sample Mean` = mean_group2, `Diff in Means` = diff_means) %>%
  kable(align = "lccc",
        caption = "Comparing Afrobarometer respondents who use social media and our sample in Tanzania", 
        label = "tab:abTZ_sub") %>%
  kable_styling(bootstrap_options = "striped")
@


\FloatBarrier
\subsection{Facebook advertising process and costs}
\label{subsec:fbads}

To sample respondents using Facebook advertisements we set up three advertisements in each country that ran between June 12 and June 26, 2019. All ads targeted Facebook users 18 years and older. The first ad targeted the entire country, the second targeted the entire country except the major cities (Dar es Salaam in Tanzania and Nairobi in Kenya) to try and get a more diverse sample that also included rural residents, and the third targeted specific geographic areas based on their close proximity to the location of refugees in the country (near Garissa in Kenya and near Kigoma and Kasulu in Tanzania).\footnote{Despite 4-5k Facebook users viewing our ad in these specific locations near refugee camps, views only results in 5 completed surveys in each country from these specific ads. This low click-through-rate meant that the cost of each completed survey in these areas was much higher: \$5.38 in Kenya and \$3.15 in Tanzania. Given the challenge and cost of reaching these particular people we did not allocate more funds to these targeted ads.} Advertisements were run through the research page we created on Facebook. After respondents clicked on the ad they were sent to the Qualtrics survey that began by obtaining informed consent. 

Table \ref{tab:fbads} presents the overall reach and cost of the advertisements we ran on Facebook to recruit respondents in Kenya and Tanzania. On average the advertisement cost per baseline survey was \$0.22 in Kenya and \$0.60 in Tanzania, which is dramatically cheaper than the standard in-person surveys in these countries based on our experiences. For researchers looking to cheaply and quickly recruit online respondent pools who care about internal validity, Facebook presents a useful tool to do so \citep{Rosenzweig2020}.

\begin{center}
\begin{table}[htb]
\centering
\caption{Facebook advertisement analytics for Kenya and Tanzania}
\label{tab:fbads}
\begin{tabular}{|l|r|r|}
\hline
               & Kenya    & Tanzania \\ \hline
Impressions    & 351,694  & 2,378,353   \\
Reach          & 282,067  & 1,055,799   \\
Clicks         & 7,948    & 25,315      \\
Click through rate (CTR)         & .023    & .011      \\
Survey results & 2,499      & 2,384       \\ 
Total spent    & \$539.52 & \$1,420.32  \\ \hline
\end{tabular}
\end{table}
\end{center}


\newpage
\section{Group C Match Schedule}
\label{sec:groupC}

This project takes advantage of a natural experiment of the timing and outcome of the 2019 Africa Cup of Nations, a biennial international men's football championship organized by the Confederation of African Football (CAF). That year, the tournament was the 32nd edition and it was hosted by Egypt, held from June 21 to July 19.\footnote{Typically the Africa Cup takes place in January/February, this is the first time it was held in June/July.} It also saw the number of teams expanded from 16 to 24 teams. Kenya and Tanzania were part of Group C, shown in \ref{fig:groupC}. The other two teams in this group were Algeria and Senegal, who went on to play each other in the final match. Algeria ultimately won the title. 

\begin{figure}[H]
\centering
\includegraphics[width=1\textwidth]{./figures/groupcteams.png}
\caption{2019 Africa Cup Group C background. Source: Confederation of African Football.}
\label{fig:groupC}
\end{figure}


%%% SURVEY QUESTIONS
\newpage
\section{Survey Outcome Questions}
\label{sec:SIquestions}

Below are our survey questions (Kenya version) measuring the main and secondary (presented in the SI) outcomes of interest. The Tanzanian version just replaces ``Kenya'' with ``Tanzania'' and vice versa when asking about the rival.

\subsection{Nationalism and Levels of Identification}

\begin{changemargin}{1cm}{2cm} 
\tt{\small{
\noindent Q. \textbf{National Pride}: How much do you agree or disagree with the following statement?  It makes me proud to be called a Kenyan.\\
\noindent 1 .....	Strongly disagree\\
2 .....	Somewhat disagree\\
3 .....	Neither disagree or agree\\
4 .....	Somewhat agree\\
5 .....	Strongly agree\\ 

\noindent Q. \textbf{National vs. Ethnic}: Let us suppose that you had to choose between being a Kenyan and being a member of your ethnic group, which of the following statements best expresses your feelings?\\
\noindent 1 .....	I feel only a member of my ethnic group\\
2 .....	I feel more a member of my ethnic group than Kenyan\\
3 .....	I feel equally Kenyan and a member of my ethnic group\\
4 .....	I feel more Kenyan than a member of my ethnic group\\
5 .....	I only feel Kenyan\\ 

\noindent Q. \textbf{African Pride}: How much do you agree or disagree with the following statement?  It makes me proud to be called an African.\\
\noindent 1 .....	Strongly disagree\\
2 .....	Somewhat disagree\\
3 .....	Neither disagree or agree\\
4 .....	Somewhat agree\\
5 .....	Strongly agree
}}
\end{changemargin}


\subsection{National Identification Mechanisms from \citet{Robinson:2016}}

\begin{changemargin}{1cm}{2cm} 
\tt{\small{
\noindent Q. \textbf{Affective 1}: We all belong to many different types of groups. Which of the following statements is closest to your view?\\
\noindent 0 .....	While I am proud of my Kenyan identity, there are other groups that I feel more proud to belong to.\\
1 .....	While I am proud of many of the groups to which I belong, I am most proud of my Kenyan identity.\\

\noindent Q. \textbf{Affective 2}: Imagine that a story in the international media criticized Kenyans. Which of the following statements is closest to how you would feel?\\
\noindent 0 ..... I would not like it, but it would not feel like a personal insult.\\
1 .....	I would not like it, and I would feel personally insulted.\\

\noindent Q. \textbf{Behavioral 1}: Which of the following statements is closest to your view?\\
\noindent 0 ..... How well other Kenyans are doing does not really affect how well I am doing.\\
1 .....	How well I am doing really depends on how well other Kenyans are doing.\\

\noindent Q. \textbf{Behavioral 2}: Which of the following statements is closest to your view?\\
\noindent 0 .....	Kenyans from different regions of the country do not really have to rely on one another to manage.\\
1 ..... Kenyans from different regions of the country cannot manage without help from Kenyans in other regions.\\

\noindent Q. \textbf{Cognitive 1}: Which of the following statements is closest to your view?\\
\noindent 0 ..... I see myself as quite different from most Kenyans.  \\
1 .....	I see myself as quite similar to most Kenyans.\\

\noindent Q. \textbf{Cognitive 2}: Which of the following statements is closest to your view?\\
\noindent 0 ..... Because there is a lot of cultural variety among Kenyans, there is very little that makes us the same.\\
1 .....	Even though there is a lot of cultural variety among Kenyans, we are more the same than we are different.
}}
\end{changemargin}


\subsection{Attitudes towards Refugees}

\begin{changemargin}{1cm}{2cm} 
\tt{\small{
How much do you agree or disagree with the following statements?\\
\noindent Q. \textbf{Refugee Diversity}: Refugees positively contribute to diversity in Kenya.\\
\noindent Q. \textbf{Refugee Crime}: Refugees increase local crime in Kenya.\\
\noindent Q. \textbf{Refugee Disease}: Refugees bring disease in Kenya.\\
\noindent Q. \textbf{Refugee Economy}: Refugees help improve the local economy in Kenya.\\
\noindent 1 .....	Strongly disagree\\
2 .....	Somewhat disagree\\
3 .....	Neither disagree or agree\\
4 .....	Somewhat agree\\
5 .....	Strongly agree
}}
\end{changemargin}

%\item Would you be willing to write a message in support of refugees that we will post anonymously on social media?

\subsection{Allocate government resources to different groups}

\begin{changemargin}{1cm}{2cm} 
\tt{\small{
\noindent Suppose the Kenyan government has a limited budget to distribute across 6 types of children in need living in Kenya. How would you advise the government to distribute these funds? Please allocate 10 shares across these categories that determine where the money will be sent (must add up to 10).\\
\noindent 1) Kenyan children of my ethnic group\\
2) Kenyan children in my community / neighborhood\\
3) Refugee children\\
4) Any Kenyan children\\ 
5) Any Tanzanian children\\
6) Any African children (order randomized)
}}
\end{changemargin}


%%% REFUGEE MESSAGE CODING
\newpage
\subsection{Refugee Message Coding}
\label{sec:SImsgcoding}

This section describes how our research assistant coded open-ended respondent comments that were about refugees based on the following dimensions -- cultural, economic, security, humanitarian, other. It is possible for comments have more than one code. 

\textbf{Cultural} = "C": cultural messages include any mention of language, religion, traditions, same people being separated by borders, etc. An example of a cultural message is: "I love to to tell them to feel free and be part of the society. Language and culture differences should not make them to feel alone in the country they are in.Also the leaders in our country it is best to observe the way to lead citizens to avoid creating hostility" and  “we are human beings and we are all equal in living freely without borders, refugees are part of our society and we are not supposed to discriminate them.”

\textbf{Economic} = "E": economic messages include any mention of jobs, resource, money or things of that nature. One example is: "Refugees should be treated like any other normal person and helped with basic necessities and jobs to help better their lives"

\textbf{Security} = "S": security messages include any mention of risks of security, crime, terrorism, etc. Example: "Anyone who feels unsafe or in forced insecurity in their country deserves a safe haven elsewhere. More so, help to get over their troubles and work towards a fulfilling life. We are all passing by in this world."

\textbf{Humanitarian / Deserving of Rights} = "H" : messages related to treating all humans with dignity/respect and refugees having the right to exist / live in the country, etc.. Example: "Refugees are supposed to be given equal freedom as other citizens"

\textbf{Other} = "O": Messages that do not include any mention of culture, economic, or security topics can be coded as other with a "O".


%%% SURVEY PRIMES, MECHANISMS, RIVAL EFFECTS
\newpage
\section{Additional Analyses}
\subsection{Marginal Effects of Survey Primes}
\label{sec:SImargfx}

<<MargModelFunctions, eval = TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, message=FALSE>>=

# Examine marginal effects of the survey primes on their own (taking out Win), with country fixed effects
run_mods_marg <- function(data, ctrl_formula = ~ female + 
                       age_numb2 + 
                       edu + 
                       urban + 
                       livedout + 
                       ref_know + 
                       job + 
                       hh_wealth + 
                       voted_last2 + 
                       polclose + 
                       religion2 + 
                       religiosity +
                       UserLanguage_b + 
                       #football_interest +
                       Period +
                       country){
  
  ## Get covariates
  cov_terms <- terms(ctrl_formula)
  
  ## Analysis
  est_df <- data %>% dplyr::select(labels(cov_terms), 
                  MatchInfo,
                  Diversity,
                  PanAfrica,
                  SurvPrime,
                  starts_with("idcircle_"),
                  starts_with("nateth"),
                  starts_with("natpride"),
                  starts_with("ethpride"),
                  starts_with("afrpride"),
                  #starts_with("affective_1"),
                  #starts_with("affective_2"),
                  #starts_with("behavioral_1"),
                  #starts_with("behavioral_2"),
                  #starts_with("cognitive_1"),
                  #starts_with("cognitive_2"),
                  #starts_with("affective_std"),
                  #starts_with("behavioral_std"),
                  #starts_with("cognitive_std"),
                  #starts_with("oth_eth"),
                  #starts_with("oth_nonpartisan"),
                  #starts_with("oth_noneth"),
                  #starts_with("oth_rival"),
                  #starts_with("oth_econmig"),
                  #starts_with("oth_refugee"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"),
                  starts_with("ref_disease_recode"),
                  starts_with("ref_econ"),
                  #starts_with("govcit_recode"),
                  #starts_with("govbord_recode"),
                  #starts_with("eamove"),
                  starts_with("ref_post"),
                  starts_with("nat_govspend_"),
                  #starts_with("comm_coeth_premium"),
                  #starts_with("comm_conat_premium"),
                  #starts_with("comm_20eth_response"),
                  #starts_with("comm_80eth_response"),
                  #starts_with("comm_20nat_response"),
                  #starts_with("comm_80nat_response")
                  ) %>%
    dplyr::select(-contains("_DO_")) %>%
    mutate(respid = 1:n()) %>%
    gather(key = response, value = value, 
           -c(labels(cov_terms), MatchInfo, Diversity, PanAfrica, SurvPrime,
              respid)) %>% 
    mutate(time = case_when(str_ends(response, "_b")~"Baseline",
                            str_ends(response, "_e")~"Endline",
                            TRUE~"ruh-roh"),
           response = str_sub(response, 1, -3)) %>%
    group_by(response) %>%
    do({
      
      ## Additional effect of each prime
      mod_inter <- try(lm_robust(update(value ~ MatchInfo*time + 
                                          Diversity*time + PanAfrica*time, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>%
        filter(grepl(":", term))
      
      ## Additional effect of any prime
      mod_anyprime <-  try(lm_robust(update(value ~ SurvPrime*time, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>% 
        filter(term == "SurvPrime:timeEndline")
      
      ## Clean and output
      bind_rows(mod_inter, mod_anyprime) %>%
        mutate(term = case_when(grepl("MatchInfo", term)~"MatchInfo",
                                grepl("Diversity", term)~"Diversity",
                                grepl("PanAfrica", term)~"PanAfrica",
                                grepl("SurvPrime", term)~"Any Prime",
                                TRUE~"ruh-roh"),
               term = fct_relevel(term, "Any Prime"))
    }) 
  
  return(est_df)  
  
}

## Estimate
teff_df_marg <- run_mods_marg(data = ACUP %>% filter(doublerand == 0))

teff_df_marg_tz <- run_mods_marg(data = ACUP %>% filter(doublerand == 0 & country == "Tanzania"),
                                 ctrl_formula = ~ female + age_numb2 + edu + urban + livedout + ref_know + 
                                   job + hh_wealth + voted_last2 + polclose + religion2 + religiosity +UserLanguage_b + Period)

teff_df_marg_ky <- run_mods_marg(data = ACUP %>% filter(doublerand == 0 & country == "Kenya"),
                                 ctrl_formula = ~ female + age_numb2 + edu + urban + livedout + ref_know + 
                                   job + hh_wealth + voted_last2 + polclose + religion2 + religiosity +UserLanguage_b + Period)

teff_df_marg_bycountry <- bind_rows(
  teff_df_marg %>% mutate(country = "All"),
  teff_df_marg_tz %>% mutate(country = "Tanzania"),
  teff_df_marg_ky %>% mutate(country = "Kenya")
)

@

<<Pride_marg, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 4.3, fig.pos ='H', fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure shows marginal effects of the survey primes for national pride, national versus ethnic attachment, African pride, and amount of government resources (out of 10 tokens) that should be distributed to conational children (regardless of ethnicity). This first estimate (black) includes all respondents and country fixed effects; the second (red) and third (blue) are subsetted analyses for Kenya and Tanzania. All point estimates include 95$\\%$ CIs.">>=

pd <- position_dodge(0.5) # move them .05 to the left and right

## Pride outcomes
results <- teff_df_marg_bycountry %>% 
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
  response = fct_relevel(response, "National Pride", 
                         "National vs. Ethnic", 
                         "African Pride"),
  term = fct_relevel(term, 
                         "Any Prime", 
                         "MatchInfo",
                         "Diversity",
                         "PanAfrica"),
  country = fct_relevel(country, 
                         "Tanzania", 
                         "Kenya",
                         "All"),
  statsig = case_when(p.value < .05~"statsig", TRUE~"notstatsig")) %>%
  ggplot(aes(x = reorder(term, desc(term)), 
             y = estimate, colour = country, group = country)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("blue", "red", "black")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.25,0,.25), limits = c(-.3, .5)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend National
results2 <- teff_df_marg_bycountry %>% ungroup() %>%
  filter(grepl("nat_govspend_4_1", response)) %>%
  mutate(response = "Resources for Conationals",
          term = fct_relevel(term, 
                         "Any Prime", 
                         "MatchInfo",
                         "Diversity",
                         "PanAfrica"),
          country = fct_relevel(country, 
                         "Tanzania", 
                         "Kenya",
                         "All"),
  statsig = case_when(p.value < .05~"statsig", TRUE~"notstatsig")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = country, group = country)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("blue", "red", "black")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.4,0,.4), limits = c(-.8, .8)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(results + results2 + plot_layout(widths = c(3.5, 1))) 

@

<<RefAtt_marg, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 4.3, fig.pos ='H', fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure shows marginal effects of the survey primes for refugee attitudes, amount of government resources (out of 10 tokens) that should be distributed to refugee children. This first estimate (black) includes all respondents and country fixed effects; the second (red) and third (blue) are subsetted analyses for Kenya and Tanzania. All point estimates include 95$\\%$ CIs.">>=

pd <- position_dodge(0.5) # move them .05 to the left and right

## Attitude outcomes
results <- teff_df_marg_bycountry %>% filter(response %in% c("ref_crime_recode", 
                                                "ref_diverse",
                                                "ref_disease_recode", 
                                                "ref_econ")) %>%
  ungroup() %>%
  mutate(
    response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", 
                           "Refugee Crime", 
                           "Refugee Disease", 
                           "Refugee Economy"),
    term = fct_relevel(term, 
                         "Any Prime", 
                         "MatchInfo",
                         "Diversity",
                         "PanAfrica"),
    country = fct_relevel(country, 
                         "Tanzania", 
                         "Kenya",
                         "All")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = country, group = country)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_colour_manual(values = c("blue", "red", "black")) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend Refugee
results2 <- teff_df_marg_bycountry %>% ungroup() %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees",
          term = fct_relevel(term, 
                         "Any Prime", 
                         "MatchInfo",
                         "Diversity",
                         "PanAfrica"),
         country = fct_relevel(country, 
                         "Tanzania", 
                         "Kenya",
                         "All")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = country, group = country)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.4,0,.4), limits = c(-.6, .8)) + 
  scale_colour_manual(values = c("blue", "red", "black")) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(results + results2 + plot_layout(widths = c(4, 1))) 

@

Figures \ref{fig:Pride_marg} and \ref{fig:RefAtt_marg} plot the marginal effects of the experimental survey primes (relative to the control condition of no prime), for the whole sample (black) with country fixed effects and for Kenya (red) and Tanzania (blue) separately. With respect to Figure \ref{fig:Pride_marg}, interestingly, primes have no effect in Tanzania among respondents when they were surveyed after the loss of the game. In Kenya, among respondents from the winning team, the primes have a positive effect, relative to the control condition, for the national pride and African pride outcomes. Looking at Figure \ref{fig:RefAtt_marg}, any prime has a negative affect on perceptions of refugees contributing positively to diversity in the country among Tanzanians but has a positive effect among Kenyans. In Kenya, this may be due to the fact that the primes reframe the win. In Tanzania, the primes emphasize the game and may increase negative sentiments among Tanzanian respondents which may be transferred to attitudes toward cultural attributes of refugees. However, the primes overall have the opposite effect in Tanzania where they make respondents respond more positively when asked whether refugees contribute to the nation's economy.


\newpage
\subsection{Results on Nationalism Mechanisms}
\label{sec:SImech}

<<ModelFunctions_SI, eval = TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, message=FALSE>>=

## Get main results - treatment effects
teff_df <- run_mods(data = ACUP %>% filter(doublerand == 0))

## Function to show pre/post change
prepost_df <- ACUP %>% filter(doublerand == 0) %>%
  dplyr::select(country, 
         starts_with("idcircle_"),
         starts_with("nateth"),
         starts_with("natpride"),
         starts_with("ethpride"),
         starts_with("afrpride"),
         starts_with("affective_1"),
         starts_with("affective_2"),
         starts_with("behavioral_1"),
         starts_with("behavioral_2"),
         starts_with("cognitive_1"),
         starts_with("cognitive_2"),
         starts_with("affective_std"),
         starts_with("behavioral_std"),
         starts_with("cognitive_std"),
         #starts_with("oth_eth"),
         #starts_with("oth_nonpartisan"),
         #starts_with("oth_noneth"),
         #starts_with("oth_rival"),
         #starts_with("oth_econmig"),
         #starts_with("oth_refugee"),
         starts_with("ref_crime_recode"),
         starts_with("ref_diverse"),
         starts_with("ref_disease_recode"),
         starts_with("ref_econ"),
         #starts_with("govcit_recode"),
         #starts_with("govbord_recode"),
         #starts_with("eamove"),
         starts_with("ref_post"),
         starts_with("nat_govspend_"),
         #starts_with("comm_coeth_premium"),
         #starts_with("comm_conat_premium"),
         #starts_with("comm_20eth_response"),
         #starts_with("comm_80eth_response"),
         #starts_with("comm_20nat_response"),
         #starts_with("comm_80nat_response")
         ) %>%
  dplyr::select(-contains("_DO_")) %>%
  gather(key = outcome, value = response, -c(country)) %>%
  drop_na() %>%
  mutate(time = case_when(str_sub(outcome, -2) == "_b"~"Pre",
                          str_sub(outcome, -2) == "_e"~"Post",
                          TRUE~"ruh-roh"),
         outcome = case_when(str_sub(outcome, -2) %in% c("_e", "_b")~str_sub(outcome, end=-3))) %>%
  group_by(country, time, outcome) %>%
  summarize(mean = mean(response),
            se = sd(response) / sqrt(n()),
            lower = mean - se * qnorm(.975),
            upper = mean + se * qnorm(.975)) %>%
  ungroup() %>% 
  mutate(time = fct_relevel(time, "Pre"))

## Function to show day-by-day estimates
df_byday <- ACUP %>% filter(doublerand == 0) %>%
  dplyr::select(country, 
         day_b, 
         day_e,
         starts_with("idcircle_"),
         starts_with("nateth"),
         starts_with("natpride"),
         starts_with("ethpride"),
         starts_with("afrpride"),
         starts_with("affective_1"),
         starts_with("affective_2"),
         starts_with("behavioral_1"),
         starts_with("behavioral_2"),
         starts_with("cognitive_1"),
         starts_with("cognitive_2"),
         #starts_with("oth_eth"),
         #starts_with("oth_nonpartisan"),
         #starts_with("oth_noneth"),
         #starts_with("oth_rival"),
         #starts_with("oth_econmig"),
         #starts_with("oth_refugee"),
         starts_with("ref_crime_recode"),
         starts_with("ref_diverse"),
         starts_with("ref_disease_recode"),
         starts_with("ref_econ"),
         #starts_with("govcit_recode"),
         #starts_with("govbord_recode"),
         #starts_with("eamove"),
         starts_with("ref_post"),
         starts_with("nat_govspend_"),
         #starts_with("comm_20eth_response"),
         #starts_with("comm_80eth_response"),
         #starts_with("comm_20nat_response"),
         #starts_with("comm_80nat_response")
         ) %>%
  dplyr::select(-contains("_DO_")) 
df_baseline <- df_byday %>% dplyr::select(country, ends_with("_b")) %>%
  rename_at(vars(ends_with("_b")), funs(str_replace(., "_b", "")))
df_endline <- df_byday %>% dplyr::select(country, ends_with("_e")) %>%
  rename_at(vars(ends_with("_e")), funs(str_replace(., "_e", "")))

df_byday <- bind_rows(df_baseline, df_endline) %>%
  gather(key = outcome, value = value, -c(country, day)) %>%
  drop_na() %>%
  group_by(country, day, outcome) %>%
  summarize(est = mean(value),
            se = sd(value) / sqrt(n()),
            lower = est - se * qnorm(.975),
            upper = est + se * qnorm(.975)) %>%
  ungroup() %>%
  mutate(day = as.Date(day))

## ggplot theme
yy_theme <- function(){
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11),
          legend.position = 'none',
          axis.text.x  = element_text(angle=0, vjust=1, hjust = 0, size=11))
  }

@

<<NatMech, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 7, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure shows results for nationalism mechanism questions. The upper plot shows the pre- and post-match means for Tanzania (blue) and Kenya (red). The lower plot shows the treatment effects. All point estimates include 95$\\%$ CIs.">>=

prepost <- prepost_df %>% filter(outcome %in% c("affective_1", "affective_2", 
                                                "behavioral_1", "behavioral_2", 
                                                "cognitive_1", "cognitive_2")) %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lwd = 1.2) + 
  geom_line(lty = "dashed") + 
  facet_grid(~ outcome) +
  labs(x = "", y = "Average Response (binary)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  yy_theme()

results <- teff_df %>% filter(response %in% c("affective_1", "affective_2", 
                                              "behavioral_1", "behavioral_2", 
                                              "cognitive_1", "cognitive_2")) %>%
  mutate(term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point() + 
  scale_y_continuous(breaks = c(-.2,0,.2), limits = c(-.3, .3)) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size =.7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

prepost / results

@

Adopting the same measures used by \citet{Robinson:2016}, we find that winning has a positive effect on ``cognitive'' nationalism. See SI Section \ref{sec:SIquestions} for the exact question wording. Cognitive 1 measures whether respondents see themselves as similar to other conationals. Cognitive 2 measures whether respondents see other conationals as more the same than different. After a national sports victory, this shared experience induces greater feelings of similarity among Kenyans more than Tanzanians (though Tanzanians have higher levels of cognitive nationalism at baseline). 


\newpage
\subsection{Effects of Win on Sentiment towards Match Rival}
\label{sec:SIrival}

<<Rival, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 5, fig.height = 3, fig.align='center', out.width= ".7\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure shows results for amount of government resources (out of 10 tokens) that should be distributed to children from rival country. The left plot shows the pre- and post-match means for Tanzania (blue) and Kenya (red). The right plot shows the treatment effects. All point estimates include 95$\\%$ CIs.">>=

## Govspend Rival pre-post
prepost <- prepost_df %>% ungroup() %>%
  filter(grepl("nat_govspend_5_1", outcome)) %>%
  mutate(outcome = "Resources for Rival") %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(aes(linetype=country))+
  annotate("text", x=2.3, y=.9, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=1.05, label= "KY", color = "red") + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  scale_y_continuous(limits = c(.5, 1.5)) + 
  yy_theme()

## Govspend Rival estimates
results <- teff_df %>% ungroup() %>%
  filter(grepl("nat_govspend_5_1", response)) %>%
  mutate(response = "Resources for Rival",
          term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(limits = c(-.4, .4)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

prepost + results

@

This section shows the effects for sentiment towards the match rival, i.e. Tanzanians about Kenyans and vice versa. We did not ask respondents separate questions on their attitudes to the match rival. But in the question about allocating amounts of government resources to various groups of children in need living in the respondent's country, category 5 was children from the rival country, i.e. Kenyan children living in Tanzania for Tanzanian respondents, and Tanzanian children living in Kenya for Kenyan respondents. Figure \ref{fig:Rival} shows that out of 10 tokens, both Kenyan and Tanzanian respondents allocate very little to the rival, about only 1 token, and this does not change post-match. The effects of the win and the survey primes are statistically and substantively null. 


\newpage
\subsection{Effects of Win on pan-African Sentiment}
\label{sec:SIanyAfrican}

<<AnyAfrican, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 5, fig.height = 3, fig.align='center', out.width= ".7\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure shows results for amount of government resources (out of 10 tokens) that should be distributed to any African children. The left plot shows the pre- and post-match means for Tanzania (blue) and Kenya (red). The right plot shows the treatment effects. All point estimates include 95$\\%$ CIs.">>=

## Govspend Any African children pre-post
prepost <- prepost_df %>% ungroup() %>%
  filter(grepl("nat_govspend_6_1", outcome)) %>%
  mutate(outcome = "Resources for Any African Children") %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(aes(linetype=country))+
  annotate("text", x=2.3, y=2.1, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=1.7, label= "KY", color = "red") + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  scale_y_continuous(limits = c(.5, 2.5)) + 
  yy_theme()

## Govspend Rival estimates
results <- teff_df %>% ungroup() %>%
  filter(grepl("nat_govspend_6_1", response)) %>%
  mutate(response = "Resources for Any African Children",
          term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(limits = c(-1, 1)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

prepost + results

@

This section does the effects for pan-African sentiment. We did not ask respondents separate questions on their pan-Africanism. But in the question about allocating amounts of government resources to various groups of children in need living in the respondent's country, category 6 was any African children. Figure \ref{fig:AnyAfrican} shows that out of 10 tokens, both Kenyan and Tanzanian respondents allocate a moderate amount to this category, which grew for both post-Match, more so for Tanzanians than Kenyans. 


%%% HETEROGENEOUS TREATMENT EFFECTS
\newpage
\section{Heterogeneous Treatment Effects Analyses}
\label{sec:SIhte}

This section shows the heterogeneous treatment effects (HTE) for the main outcomes in the paper by gender, rural or urban residence, age, household wealth, formal education, baseline national identification, whether the respondent personally knew refugees or not at baseline, and by level of stated interest in football. We do not analyze HTE by language (Swahili and English), because it maps very closely onto country (Tanzania and Kenya, respectively); or by religion since the vast majority of respondents in both countries are Christian. Please note that these HTE analyses were requested by our reviewers, and were not pre-registered.

%% groups defined as: > / <= median (only age is different, < / >=)

% gender
With respect to gender, we observe that the effect of the win on resources for conationals is larger for men than women, the reverse is true for national identification and there is no heterogeneous treatment effect of the win on national nor African pride. Overall, the effect of the primes on national and African pride is also stronger among men. Interestingly, the primes have a stronger effect among women with respect to attitudes toward refugee diversity and, to a lesser degree, resources for refugees. 

% age
Comparing treatment effects for younger (below 26 years, the median age in our sample) and older respondents (26 years and older), the effect of the win on nationalism outcomes does not vary. The primes increase African pride among younger respondents but have a mostly null effect among older respondents, while they increase resource allocation to conationals more among older respondents. The effect of the win on refugee outcomes is largely equivalent in these two subgroups, with the exception of attitudes toward refugee disease and economy. The win has a positive effect among older respondents on disease attitudes, but a null effect for younger ones. The win has a negative effect among younger respondents on economy attitudes, but null for older respondents. 
There does not seem to be much treatment effect heterogeneity among rural/urban and wealthy/poor respondents.

% edu
Among respondents with high (has some post-secondary education or above) and lower (has less then post-secondary education) education levels, we observe no treatment effect heterogeneity with respect to the game win. There is greater heterogeneity of the primes, particularly the diversity prime. 

% baseline levels of nationalism
Importantly, we also look at heterogeneous treatment effects by respondents' baseline levels of national identification. ``High'' nationals are those who said they feel more or only part of their national identity. ``Low'' national identifiers are defined as those who reported identifying equally with their national or ethnic identity or more/only with their ethnic group. We observe that the effect of the win on national and African pride is slightly larger (more positive) for low baseline nationals, but equivalent for these subgroups on the resources outcome measure. The effect of the pan-Africa prime on national and African pride is also larger among low baseline nationals, but more negative for this group with respect to the resources outcome. Interestingly, the effects of the primes on refugee diversity are larger among high baseline nationals, but more negative among low baseline nationals with respect to refugee economy. 

% know refugee
Defining respondents based on whether they said they knew a refugee during the baseline survey or not, we analyze whether any of the treatment effects we observe are moderated by personally knowing a refugee. In particular, we might expect that the negative effect of the win on attitudes with respect to refugee diversity would be weaker among respondents who know a refugee. We do not find this: both those with and without prior refugee contact are similarly affected by the win. However, we do observe a slightly more positive effect of the primes x win among respondents who knew refugees.

% football interest
With respect to stated interest in football, we see that, encouragingly, it is not the case that the main results are solely driven by effects among respondents who say they are interested in football. Those with self-reported higher and lower interest in football overall respond similarly to the win and the primes. One interesting exception is that the main effect of the win on identifying with the nation over one's ethnic group is largely driven by respondents with \textit{low} interest in football. Respondents who are more interested in football become slightly more likely (though not statically significantly) to identify with their ethnic group over the nation. We do want to note, however, that the question about interest in football was included in the endline survey (so as not to tip of respondents that our survey was about football in the baseline) and while it may be unlikely that responses to this question would have been different if measured before the game and exposure to primes, it is possible and hence these analyses should be viewed with caution. 


<<hte_formulas, eval = TRUE, echo = FALSE, tidy=TRUE>>=

## Function for running models interactively
run_mods_hte <- function(
  data, hte_var, ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
    livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
    religion2 + religiosity + UserLanguage_b + Period
){
  
  ## Get covariates
  cov_terms <- terms(ctrl_formula)
  cov_terms_labs <- labels(cov_terms)
  
  cov_terms_labs_hte <- cov_terms_labs[cov_terms_labs != hte_var]
  data <- data %>% rename(hte_var = hte_var)
  data[[hte_var]] <- data$hte_var
  
  ## Analysis
  est_df <- data %>% 
    dplyr::select(all_of(cov_terms_labs), hte_var, MatchInfo, 
                  Diversity, PanAfrica,
                  SurvPrime, starts_with("nateth"),
                  starts_with("natpride"), 
                  starts_with("afrpride"), starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"), starts_with("ref_disease_recode"),
                  starts_with("ref_econ"), starts_with("ref_post"),
                  starts_with("nat_govspend_")) %>%
    dplyr::select(-contains("_DO_")) %>%
    mutate(respid = 1:n()) %>%
    gather(key = response, value = value, 
           -c(all_of(cov_terms_labs), MatchInfo, Diversity, PanAfrica, SurvPrime,
              respid, hte_var)) %>% 
    mutate(time = case_when(str_ends(response, "_b")~"Baseline",
                            str_ends(response, "_e")~"Endline",
                            TRUE~"ruh-roh"),
           response = str_sub(response, 1, -3)) %>%
    group_by(response) %>%
    do({
      
      ## Marginalize over primes
      mod_base_hte <- try(lm_robust(update(value ~ Win*time*hte_var,
                                       reformulate(c(".",cov_terms_labs_hte))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      mod_base_orig <- try(lm_robust(update(value ~ Win*time,
                                       reformulate(c(".",cov_terms_labs))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      
      mod_base_df <- data.frame(
        estimate = c(coef(mod_base_hte)["Win:timeEndline"],
                 coef(mod_base_hte)["Win:timeEndline"] + 
                   coef(mod_base_hte)["Win:timeEndline:hte_var"]),
        std.error = c(sqrt(vcov(mod_base_hte)["Win:timeEndline", "Win:timeEndline"]),
               sqrt(vcov(mod_base_hte)["Win:timeEndline", "Win:timeEndline"] +
                      vcov(mod_base_hte)["Win:timeEndline:hte_var", "Win:timeEndline:hte_var"] + 
                      2*vcov(mod_base_hte)["Win:timeEndline", "Win:timeEndline:hte_var"])),
        hte = c(0, 1),
        term = rep("Win", 2)
      ) %>%
        bind_rows(
          mod_base_orig %>% 
            tidy() %>%
            filter(grepl("Win:timeEndline", term)) %>%
            dplyr::select(estimate, std.error, term, conf.low, conf.high) %>%
            mutate(hte = 99,
                   term = "Win")
        )
      
      ## Additional effect of each prime
      mod_inter_hte <- try(lm_robust(update(value ~ MatchInfo*time*Win*hte_var + 
                                          Diversity*time*Win*hte_var +
                                          PanAfrica*time*Win*hte_var, 
                                       reformulate(c(".", cov_terms_labs_hte))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      mod_inter_orig <- try(lm_robust(update(value ~ MatchInfo*time*Win + 
                                          Diversity*time*Win +
                                          PanAfrica*time*Win, 
                                       reformulate(c(".", cov_terms_labs))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      
      mod_inter_df <- data.frame(
        estimate = c(coef(mod_inter_hte)["MatchInfo:timeEndline:Win"],
                 coef(mod_inter_hte)["timeEndline:Win:Diversity"],
                 coef(mod_inter_hte)["timeEndline:Win:PanAfrica"],
                 coef(mod_inter_hte)["MatchInfo:timeEndline:Win"] + 
                   coef(mod_inter_hte)["MatchInfo:timeEndline:Win:hte_var"],
                 coef(mod_inter_hte)["timeEndline:Win:Diversity"] + 
                   coef(mod_inter_hte)["timeEndline:Win:hte_var:Diversity"],
                 coef(mod_inter_hte)["timeEndline:Win:PanAfrica"] + 
                   coef(mod_inter_hte)["timeEndline:Win:hte_var:PanAfrica"]
                 ),
        std.error = c(sqrt(vcov(mod_inter_hte)["MatchInfo:timeEndline:Win","MatchInfo:timeEndline:Win"]),
               sqrt(vcov(mod_inter_hte)["timeEndline:Win:Diversity","timeEndline:Win:Diversity"]),
               sqrt(vcov(mod_inter_hte)["timeEndline:Win:PanAfrica","timeEndline:Win:PanAfrica"]),
               sqrt(vcov(mod_inter_hte)["MatchInfo:timeEndline:Win","MatchInfo:timeEndline:Win"] + 
                      vcov(mod_inter_hte)["MatchInfo:timeEndline:Win:hte_var","MatchInfo:timeEndline:Win:hte_var"] + 
                      2*vcov(mod_inter_hte)["MatchInfo:timeEndline:Win","MatchInfo:timeEndline:Win:hte_var"]),
               sqrt(vcov(mod_inter_hte)["timeEndline:Win:Diversity","timeEndline:Win:Diversity"] + 
                      vcov(mod_inter_hte)["timeEndline:Win:hte_var:Diversity","timeEndline:Win:hte_var:Diversity"] + 
                      2*vcov(mod_inter_hte)["timeEndline:Win:Diversity","timeEndline:Win:hte_var:Diversity"]),
               sqrt(vcov(mod_inter_hte)["timeEndline:Win:PanAfrica","timeEndline:Win:PanAfrica"] + 
                      vcov(mod_inter_hte)["timeEndline:Win:hte_var:PanAfrica","timeEndline:Win:hte_var:PanAfrica"] + 
                      2*vcov(mod_inter_hte)["timeEndline:Win:PanAfrica","timeEndline:Win:hte_var:PanAfrica"])
               ),
        hte = c(rep(0, 3), rep(1, 3)),
        term = rep(c("MatchInfo x Win", "Diversity x Win", "PanAfrica x Win"), 2)
      ) %>%
        bind_rows(
          mod_inter_orig %>% 
            tidy() %>%
            filter(str_count(term, ":") == 2) %>%
            dplyr::select(estimate, std.error, term, conf.low, conf.high) %>%
            mutate(hte = 99,
                   term = case_when(grepl("MatchInfo", term)~"MatchInfo x Win",
                                    grepl("Diversity", term)~"Diversity x Win",
                                    TRUE~"PanAfrica x Win"))
        )
      
      ## Additional effect of any prime
      mod_anyprime_hte <-  try(lm_robust(update(value ~ SurvPrime*time*Win*hte_var, 
                                       reformulate(c(".", cov_terms_labs_hte))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      mod_anyprime_orig <-  try(lm_robust(update(value ~ SurvPrime*time*Win, 
                                       reformulate(c(".", cov_terms_labs))),
                           data = ., clusters = respid
                           ), silent = TRUE)
      
      mod_anyprime_df <- data.frame(
        estimate = c(coef(mod_anyprime_hte)["SurvPrime:timeEndline:Win"],
                 coef(mod_anyprime_hte)["SurvPrime:timeEndline:Win"] + 
                   coef(mod_anyprime_hte)["SurvPrime:timeEndline:Win:hte_var"]),
        std.error = c(sqrt(vcov(mod_anyprime_hte)["SurvPrime:timeEndline:Win","SurvPrime:timeEndline:Win"]),
               sqrt(vcov(mod_anyprime_hte)["SurvPrime:timeEndline:Win","SurvPrime:timeEndline:Win"] + 
                      vcov(mod_anyprime_hte)["SurvPrime:timeEndline:Win:hte_var","SurvPrime:timeEndline:Win:hte_var"] + 
                      2*vcov(mod_anyprime_hte)["SurvPrime:timeEndline:Win","SurvPrime:timeEndline:Win:hte_var"])),
        hte = c(0, 1),
        term = rep("Any Prime x Win", 2)
      ) %>%
        bind_rows(
          mod_anyprime_orig %>% 
            tidy() %>%
            filter(term == "SurvPrime:timeEndline:Win") %>%
            dplyr::select(estimate, std.error, term, conf.low, conf.high) %>%
            mutate(hte = 99,
                   term = "Any Prime x Win")
        )
      
      ## Clean and output
      bind_rows(mod_base_df, mod_inter_df, mod_anyprime_df)
      
    }) 
  
  return(est_df)  
  
}

yy_theme_hte <- function(){
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11),
          legend.position = 'bottom',
          axis.text.x = element_text(angle=0, vjust=0, hjust =.5 , size=10))
  }
pd <- position_dodge(.4)


@

<<estimate_models, eval = TRUE, echo = FALSE, tidy=TRUE>>=

# estimate models and save output as rdata because they take long to run

# Gender
hte_female <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                           ctrl_formula = ~Win + age_numb2 + edu + urban + 
                             livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                             religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "female") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Male", hte == 1~"Female", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Urban v Rural
hte_urban <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                          ctrl_formula = ~Win + female + age_numb2 + edu + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "urban") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Rural", hte == 1~"Urban", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Young v Old
hte_young <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                          ctrl_formula = ~Win + female + edu + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "young") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Older", hte == 1~"Younger", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Wealthy v Poor
hte_wealthy <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + ref_know + job + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "wealthy") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Low HH Wealth", hte == 1~"High HH Wealth", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# High v Low Edu
hte_highedu <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "highedu") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Low Edu", hte == 1~"High Edu", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# High v Low Baseline Nationalism
hte_highnat <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "highnat") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Low Baseline National", hte == 1~"High Baseline National", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Knows v Does not Know a Refugee at Baseline
hte_ref_know <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + UserLanguage_b + Period,
                           hte_var = "ref_know") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"No Baseline Refugee Contact", hte == 1~"Baseline Refugee Contact", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Christian v Muslim
hte_christian <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religiosity + UserLanguage_b + Period,
                           hte_var = "christian") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Not Christian", hte == 1~"Christian", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Swahili v English
hte_swahili <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + Period,
                           hte_var = "swahili") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"English", hte == 1~"Swahili", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Football Interest
hte_fbinterest <- run_mods_hte(ACUP %>% filter(doublerand == 0), 
                            ctrl_formula = ~Win + female + age_numb2 + edu + urban + 
                            livedout + ref_know + job + hh_wealth + voted_last2 + polclose + 
                            religion2 + religiosity + Period,
                           hte_var = "football_interest_bi") %>%
  ungroup() %>%
  mutate(term = fct_relevel(term, "Win", 
                            "Any Prime x Win", 
                            "MatchInfo x Win",
                            "Diversity x Win",
                            "PanAfrica x Win"),
         conf.low = coalesce(conf.low, estimate - std.error * qnorm(.975)),
         conf.high = coalesce(conf.high, estimate + std.error * qnorm(.975)),
         hte = case_when(hte == 0~"Low Football Interest", hte == 1~"High Football Interest", TRUE~"Pooled"),
         hte = fct_relevel(hte, "Pooled"))

# Save models
# save(hte_female,
#      hte_urban,
#      hte_young,
#      hte_wealthy,
#      hte_highedu,
#      hte_highnat,
#      hte_ref_know,
#      hte_christian,
#      hte_swahili,
#      hte_fbinterest,
#      file = "ACUP_HTEmodels.Rdata")


@


\newpage
\subsection{Female vs. Male}

<<hte_female, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results by gender. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$female),1))

## --------
## Figure 3
## --------
results <- hte_female %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_female %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_female %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_female %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')


@


\newpage
\subsection{Rural vs. Urban}

<<hte_urban, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results by rural versus urban. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$urban),1))

## --------
## Figure 3
## --------
results <- hte_urban %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_urban %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_urban %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_urban %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{Younger vs. Older}

<<hte_young, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results between those younger and older than the median age of 26. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$young),1))

## --------
## Figure 3
## --------
results <- hte_young %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_young %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_young %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_young %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{Wealthy vs. Poor}

<<hte_wealthy, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results between those with more and fewer than the median household wealth items of 4. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$wealthy),1))

## --------
## Figure 3
## --------
results <- hte_wealthy %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_wealthy %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_wealthy %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_wealthy %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{High vs. Low Formal Education}

<<hte_highedu, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results between those with more or less formal education than the median of 6, which is some post−secondary school. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$highedu),1))

## --------
## Figure 3
## --------
results <- hte_highedu %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_highedu %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_highedu %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_highedu %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{High vs. Low Baseline National Identification}
\label{subsec:htenat}

<<hte_highnat, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results in the paper between those with greater or less baseline national identification than 3, out of 5 levels. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$highnat),1))

## --------
## Figure 3
## --------
results <- hte_highnat %>%
  filter(response %in% c("natpride", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_highnat %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_highnat %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_highnat %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{Pre-Post Comparison for High vs. Low Baseline National Identification}
\label{subsec:preposthtenat}

Additionally, we show pre-post comparisons between high and low baseline nationalists, subsetted down to only the survey control group. It appears winning more of a positive (less of a negative) effect for low baseline nationalists for national identification and pride outcomes; and conversely a more negative effect for attitudes toward refugees. 

<<prepost_highnat, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 9, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure pre- and post-match means for Tanzania (blue) and Kenya (red) by baseline high (solid) versus low (dashed) levels of national identification. All point estimates include 95$\\%$ CIs.">>=

## Function to show pre/post change
prepost_df_natcontrol <- ACUP %>% filter(doublerand == 0 & SurvPrime == 0) %>%
  dplyr::select(country, highnat,
         starts_with("idcircle_"),
         starts_with("nateth"),
         starts_with("natpride"),
         starts_with("ethpride"),
         starts_with("afrpride"),
         starts_with("ref_crime_recode"),
         starts_with("ref_diverse"),
         starts_with("ref_disease_recode"),
         starts_with("ref_econ"),
         starts_with("ref_post"),
         starts_with("nat_govspend_"),
         ) %>%
  dplyr::select(-contains("_DO_")) %>%
  gather(key = outcome, value = response, -c(country, highnat)) %>%
  drop_na() %>%
  mutate(time = case_when(str_sub(outcome, -2) == "_b"~"Pre",
                          str_sub(outcome, -2) == "_e"~"Post",
                          TRUE~"ruh-roh"),
         outcome = case_when(str_sub(outcome, -2) %in% c("_e", "_b")~str_sub(outcome, end=-3))) %>%
  group_by(country, time, highnat, outcome) %>%
  summarize(mean = mean(response),
            se = sd(response) / sqrt(n()),
            lower = mean - se * qnorm(.975),
            upper = mean + se * qnorm(.975)) %>%
  ungroup() %>% 
  mutate(time = fct_relevel(time, "Pre"))

## Plots

## Pride outcomes pre-post
prepost <- prepost_df_natcontrol %>% filter(outcome %in% c("natpride", "nateth", "afrpride")) %>%
  ungroup() %>%
  mutate(
    outcome = case_when(outcome == "natpride"~"National Pride",
                        outcome == "nateth"~"National vs. Ethnic",
                        outcome == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
    outcome = fct_relevel(outcome, "National Pride", "National vs. Ethnic", "African Pride"),
    highnat = case_when(highnat == 1~"High Baseline Nationalism", TRUE~"Low Baseline Nationalism"),
    groupvar = paste0(country, highnat)
  ) %>%
  ggplot(aes(time, mean, group = groupvar, colour = country)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lwd = 1.2) + 
  geom_line(aes(lty = highnat))+
  facet_grid(~ outcome) +
  labs(x = "", y = "Average Response (5pt scale)") + 
  scale_colour_manual(values = c("red", "blue")) +
  #scale_y_continuous(breaks = c(3, 4, 5), limits = c(3, 5)) + 
  yy_theme() +
  theme(legend.position = 'bottom')

prepost2 <- prepost_df_natcontrol %>% ungroup() %>%
  filter(grepl("nat_govspend_4_1", outcome)) %>%
  mutate(outcome = "Resources for Conationals",
        highnat = case_when(highnat == 1~"High Baseline Nationalism", TRUE~"Low Baseline Nationalism"),
        groupvar = paste0(country, highnat)) %>%
  ggplot(aes(time, mean, group = groupvar, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(aes(lty = highnat))+
  annotate("text", x=2.3, y=2.5, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=2.36, label= "KY", color = "red") + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  #scale_y_continuous(breaks = c(2, 2.5, 3), limits = c(2, 3)) + 
  yy_theme()

prepost3 <- prepost_df_natcontrol %>% filter(outcome %in% c("ref_crime_recode", 
                                                "ref_diverse",
                                                "ref_disease_recode", 
                                                "ref_econ")) %>%
  ungroup() %>%
  mutate(
    outcome = case_when(outcome == "ref_crime_recode"~"Refugee Crime",
                        outcome == "ref_diverse"~"Refugee Diversity",
                        outcome == "ref_disease_recode"~"Refugee Disease",
                        outcome == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    outcome = fct_relevel(outcome, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),
    highnat = case_when(highnat == 1~"High Baseline Nationalism", TRUE~"Low Baseline Nationalism"),
    groupvar = paste0(country, highnat)
  ) %>%
  ggplot(aes(time, mean, group = groupvar, colour = country)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lwd = 1.2) + 
  geom_line(aes(lty = highnat))+
  facet_grid(~ outcome) +
  labs(x = "", y = "Average Response (5pt scale)") + 
  scale_colour_manual(values = c("red", "blue")) +
  #scale_y_continuous(breaks = c(3, 4, 5), limits = c(3, 5)) + 
  yy_theme() +
  theme(legend.position = 'bottom')

prepost4 <- prepost_df_natcontrol %>% ungroup() %>%
  filter(grepl("nat_govspend_3_1", outcome)) %>%
  mutate(outcome = "Resources for Refugees",
        highnat = case_when(highnat == 1~"High Baseline Nationalism", TRUE~"Low Baseline Nationalism"),
        groupvar = paste0(country, highnat)) %>%
  ggplot(aes(time, mean, group = groupvar, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(aes(lty = highnat))+
  annotate("text", x=2.3, y=2.5, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=2.36, label= "KY", color = "red") + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  #scale_y_continuous(breaks = c(2, 2.5, 3), limits = c(2, 3)) + 
  yy_theme()


(prepost + prepost2 + plot_layout(widths = c(3.5, 1))) /
(prepost3 + prepost4 + plot_layout(widths = c(3.5, 1)))

@


\newpage
\subsection{Knows vs. Does not Know Any Refugees at Baseline}

<<hte_ref_know, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results in the paper between those who know versus do not know any refugees at baseline. All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$ref_know),1))

## --------
## Figure 3
## --------
results <- hte_ref_know %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_ref_know %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_ref_know %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_ref_know %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@


\newpage
\subsection{High vs. Low Interest in Football, reported at Endline}

<<hte_fbinterest, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure compares the main results in the paper between those who reported high versus low interest in football (reported at endline). All point estimates include 95$\\%$ CIs.">>=

#knitr::kable(prop.table(table(ACUP$country, ACUP$football_interest_bi),1))

## --------
## Figure 3
## --------
results <- hte_fbinterest %>%
  filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.25,0,.25)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_fbinterest %>%
  filter(response %in% c("nat_govspend_4_1")) %>%
  mutate(response = "Resources for Conationals") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(3.5, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

## --------
## Figure 4
## --------
results <- hte_fbinterest %>%
  filter(response %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ")) %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte()

results2 <- hte_fbinterest %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees") %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = hte, group = hte)) + 
  geom_point(size = 2, position = pd) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7, position = pd) + 
  scale_colour_manual(values = c("black", "blue", "red")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  #scale_y_continuous(breaks = c(-.4,0,.4)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme_hte() +
  theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

(results + results2 + 
    plot_layout(widths = c(4, 1), guides = "collect")) & 
  theme(legend.position = 'bottom')

@



%%% 3 DAY BLOCK ANALYSES
\newpage
\section{Cross-Sectional Analysis by 3-day bins}

\subsection{Effects of Win by 3-day bins for Main Outcomes}
\label{sec:SI3daycoefs}

<<threeday_SI, eval = TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, message=FALSE>>=

ctrl_formula = ~Win + 
  female + 
  age_numb2 + 
  edu + 
  urban + 
  livedout + 
  ref_know + 
  job + 
  hh_wealth + 
  voted_last2 + 
  polclose +
  religion2 + 
  religiosity + 
  UserLanguage_b

cov_terms <- terms(ctrl_formula)
df_prep_laglead <- ACUP %>% filter(doublerand == 0) %>% 
  dplyr::select(labels(cov_terms), 
                day_b, day_e,
                  MatchInfo,
                  Diversity,
                  PanAfrica,
                  SurvPrime, 
                  starts_with("idcircle_"),
                  starts_with("nateth"),
                  starts_with("natpride"),
                  starts_with("ethpride"),
                  starts_with("afrpride"),
                  #starts_with("affective_1"),
                  #starts_with("affective_2"),
                  #starts_with("behavioral_1"),
                  #starts_with("behavioral_2"),
                  #starts_with("cognitive_1"),
                  #starts_with("cognitive_2"),
                  #starts_with("affective_std"),
                  #starts_with("behavioral_std"),
                  #starts_with("cognitive_std"),
                  #starts_with("oth_eth"),
                  #starts_with("oth_nonpartisan"),
                  #starts_with("oth_noneth"),
                  #starts_with("oth_rival"),
                  #starts_with("oth_econmig"),
                  #starts_with("oth_refugee"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"),
                  starts_with("ref_disease_recode"),
                  starts_with("ref_econ"),
                  #starts_with("govcit_recode"),
                  #starts_with("govbord_recode"),
                  #starts_with("eamove"),
                  starts_with("ref_post"),
                  starts_with("nat_govspend_")
                  #starts_with("comm_coeth_premium"),
                  #starts_with("comm_conat_premium"),
                  #starts_with("comm_20eth_response"),
                  #starts_with("comm_80eth_response"),
                  #starts_with("comm_20nat_response"),
                  #starts_with("comm_80nat_response")
                ) %>%
  mutate(respid = 1:n())

df_baseline <- df_prep_laglead %>% dplyr::select(-ends_with("_e")) %>%
  rename_at(vars(ends_with("_b")), funs(str_replace(., "_b", ""))) %>%
  rename(UserLanguage_b = UserLanguage)
df_endline <- df_prep_laglead %>% dplyr::select(-c(day_b, natpride_b, afrpride_b)) %>%
  rename_at(vars(ends_with("_e")), funs(str_replace(., "_e", "")))

## Game was on 6/27
df_laglead <- bind_rows(df_baseline, df_endline) %>%
  mutate(date_range = case_when(day %in% c("2019-06-12", "2019-06-13", "2019-06-14")~"6/12 - 6/14",
                                day %in% c("2019-06-15", "2019-06-16", "2019-06-17")~"6/15 - 6/17",
                                day %in% c("2019-06-18", "2019-06-19", "2019-06-20")~"6/18 - 6/20",
                                day %in% c("2019-06-21", "2019-06-22", "2019-06-23")~"6/21 - 6/23",
                                day %in% c("2019-06-24", "2019-06-25", "2019-06-26")~"6/24 - 6/26",
                                day %in% c("2019-06-27", "2019-06-28", "2019-06-29", "2019-06-30")~"6/27 - 6/30",
                                day %in% c("2019-07-01", "2019-07-02", "2019-07-03")~"7/01 - 7/03",
                                day %in% c("2019-07-04", "2019-07-05", "2019-07-06")~"7/04 - 7/06",
                                day %in% c("2019-07-07", "2019-07-08", "2019-07-09")~"7/07 - 7/09",
                                day %in% c("2019-07-10", "2019-07-11", "2019-07-12", "2019-07-13")~"7/10 - 7/13",
                                TRUE~"ruh-roh"),
         date_range = fct_relevel(date_range, "6/24 - 6/26"))

@

<<3day_plots, eval = TRUE, echo = FALSE, tidy=TRUE, fig.pos='H', fig.width = 9, fig.height = 7, fig.align='center', out.width= ".92\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure plots the effect of winning on main outcomes for 10 dummies indicating 3-day blocks from 15 days before to 15 days after the match day on June 27. The coefficient for the period between 3 to 1 days before the match is normalized to zero. In the regressions, we include the usual controls. All point estimates include 95$\\%$ CIs.">>=

## Natpride
laglead_natpride <- lm_robust(update(natpride ~ Win*date_range, 
                                     reformulate(c(".",labels(cov_terms)))),
                         data = df_laglead, clusters = respid)

laglead_natpride_plot <- tidy(laglead_natpride) %>% filter(grepl("Win:", term)) %>%
  mutate(term = gsub("Win:date_range", "", term),
         term = case_when(term == "Win"~"6/12 - 6/14",
                          TRUE~term)) %>%
  bind_rows(tibble(term = "6/24 - 6/26", estimate = 0)) %>%
  ggplot(aes(term, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .3) + 
  geom_hline(aes(yintercept = 0), lty = "dashed") + 
  geom_vline(aes(xintercept = 5.5), colour="red") + 
  labs(x = "Date windows", y = "ATE of Win relative to 3 days before match") + 
  ggtitle("National Pride") +
  ylim(-.75,.75) +
  yy_theme() +
  theme(axis.text.x = element_text(hjust=1, angle = 45),
        plot.title = element_text(size = 13))

## NatEth
laglead_nateth <- lm_robust(update(nateth ~ Win*date_range, 
                                     reformulate(c(".",labels(cov_terms)))),
                         data = df_laglead, clusters = respid)

laglead_nateth_plot <- tidy(laglead_nateth) %>% filter(grepl("Win:", term)) %>%
  mutate(term = gsub("Win:date_range", "", term),
         term = case_when(term == "Win"~"6/12 - 6/14",
                          TRUE~term)) %>%
  bind_rows(tibble(term = "6/24 - 6/26", estimate = 0)) %>%
  ggplot(aes(term, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .3) + 
  geom_hline(aes(yintercept = 0), lty = "dashed") + 
  geom_vline(aes(xintercept = 5.5), colour="red") + 
  labs(x = "Date windows", y = "ATE of Win relative to 3 days before match") + 
  ggtitle("National vs. Ethnic") +
  ylim(-.75,.75) +
  yy_theme() +
  theme(axis.text.x = element_text(hjust=1, angle = 45),
        plot.title = element_text(size = 13))

## Afrpride
laglead_afrpride <- lm_robust(update(afrpride ~ Win*date_range, 
                                     reformulate(c(".",labels(cov_terms)))),
                         data = df_laglead, clusters = respid)

laglead_afrpride_plot <- tidy(laglead_afrpride) %>% filter(grepl("Win:", term)) %>%
  mutate(term = gsub("Win:date_range", "", term),
         term = case_when(term == "Win"~"6/12 - 6/14",
                          TRUE~term)) %>%
  bind_rows(tibble(term = "6/24 - 6/26", estimate = 0)) %>%
  ggplot(aes(term, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .3) + 
  geom_hline(aes(yintercept = 0), lty = "dashed") + 
  geom_vline(aes(xintercept = 5.5), colour="red") + 
  labs(x = "Date windows", y = "ATE of Win relative to 3 days before match") + 
  ggtitle("African Pride") +
  ylim(-.75,.75) +
  yy_theme() +
  theme(axis.text.x = element_text(hjust=1, angle = 45),
        plot.title = element_text(size = 13))

## Resources for Conationals
laglead_nat_govspend_4_1 <- lm_robust(update(nat_govspend_4_1 ~ Win*date_range, 
                                     reformulate(c(".",labels(cov_terms)))),
                         data = df_laglead, clusters = respid)

laglead_nat_govspend_4_1_plot <- tidy(laglead_nat_govspend_4_1) %>% filter(grepl("Win:", term)) %>%
  mutate(term = gsub("Win:date_range", "", term),
         term = case_when(term == "Win"~"6/12 - 6/14",
                          TRUE~term)) %>%
  bind_rows(tibble(term = "6/24 - 6/26", estimate = 0)) %>%
  ggplot(aes(term, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .3) + 
  geom_hline(aes(yintercept = 0), lty = "dashed") + 
  geom_vline(aes(xintercept = 5.5), colour="red") + 
  labs(x = "Date windows", y = "ATE of Win relative to 3 days before match") + 
  ggtitle("Resources for Conationals") +
  ylim(-1,1) +
  yy_theme() +
  theme(axis.text.x = element_text(hjust=1, angle = 45),
        plot.title = element_text(size = 13))


# Plot
laglead_natpride_plot / laglead_nateth_plot /
laglead_afrpride_plot / laglead_nat_govspend_4_1_plot + plot_layout(ncol=2)

@

This section shows a lag and leads analysis of winning on the Nationalism and pride outcomes. Figure \ref{fig:3day_plots} plots the effects of winning (difference between Kenyan and Tanzanian respondents) using 3-day binned intervals pre- and post- the match on June 27, relative to the baseline of June 24 - 26, 3 days before the match (meaning that effect is normalized to zero). For National Pride, National vs. Ethnic, and Resources for Conationals, we observe no effect before the match, but a positive effect of winning through July 6.\footnote{July 7th (``saba saba'') is a public holiday in Tanzania celebrating the founding of the ruling party. Hence, it is not surprising that any glimpse of an effect for Kenyans disappears after this day.} In comparison, we see no effects for African pride during this period. These results confirm our theoretical predictions. 


\newpage
\subsection{Win Loss Comparison Analysis using 3-day bins}
\label{sec:SIwinloss3day}

<<3day_winloss_Pride, eval = TRUE, echo = FALSE, tidy=TRUE, fig.pos='H', fig.width = 10, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="All point estimates include 95$\\%$ CIs.">>=

# INCLUDE DASHED LINES WHEN THE GAMES ARE

df_winloss_threeday <- ACUP %>% filter(doublerand == 0 & SurvPrime == 0) %>%
  dplyr::select(StartDate_e, StartDate_b, Win, 
                  starts_with("nateth"),
                  starts_with("natpride"), 
                  starts_with("afrpride"), 
                  starts_with("nat_govspend_4_1"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"), starts_with("ref_disease_recode"),
                  starts_with("ref_econ"), 
                  starts_with("nat_govspend_3_1")) %>%
  pivot_longer(cols = c(starts_with("nateth"),
                  starts_with("natpride"), 
                  starts_with("afrpride"), 
                  starts_with("nat_govspend_4_1"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"), starts_with("ref_disease_recode"),
                  starts_with("ref_econ"), 
                  starts_with("nat_govspend_3_1"))) %>%
  mutate(name = str_sub(name, 1, -3))

## Daily comparison
df_gb <- df_winloss_threeday %>% 
  mutate(time_period = as.Date(StartDate_b)) %>%
  mutate(time_period = case_when(time_period %in% as.Date(c("2019-06-12", "2019-06-13", "2019-06-14"))~"6/12 - 6/14",
                                time_period %in% as.Date(c("2019-06-15", "2019-06-16", "2019-06-17"))~"6/15 - 6/17",
                                time_period %in% as.Date(c("2019-06-18", "2019-06-19", "2019-06-20"))~"6/18 - 6/20",
                                time_period %in% as.Date(c("2019-06-21", "2019-06-22", "2019-06-23"))~"6/21 - 6/23",
                                time_period %in% as.Date(c("2019-06-24", "2019-06-25", "2019-06-26"))~"6/24 - 6/26",
                                TRUE~"ruh-roh")) %>%
  drop_na() %>%
  group_by(time_period, Win, name) %>%
  summarize(est = mean(value),
            se = sqrt(var(value) / n()),
            n = n(),
            lower = est - se * qnorm(.975), 
            upper = est + se * qnorm(.975)) %>%
  filter(se != 0)

df_p <- df_winloss_threeday %>%
  mutate(time_period = as.Date(StartDate_e)) %>%
  mutate(time_period = case_when(time_period %in% as.Date(c("2019-06-27", "2019-06-28", "2019-06-29", "2019-06-30"))~"6/27 - 6/30",
                                time_period %in% as.Date(c("2019-07-01", "2019-07-02", "2019-07-03"))~"7/01 - 7/03",
                                time_period %in% as.Date(c("2019-07-04", "2019-07-05", "2019-07-06"))~"7/04 - 7/06",
                                time_period %in% as.Date(c("2019-07-07", "2019-07-08", "2019-07-09"))~"7/07 - 7/09",
                                time_period %in% as.Date(c("2019-07-10", "2019-07-11", "2019-07-12", "2019-07-13"))~"7/10 - 7/13",
                                TRUE~"ruh-roh")) %>%
  drop_na() %>%
  group_by(time_period, Win, name) %>%
  summarize(est = mean(value),
            se = sqrt(var(value) / n()),
            n = n(),
            lower = est - se * qnorm(.975), 
            upper = est + se * qnorm(.975)) %>%
  filter(se != 0)

df_winloss_plot <- bind_rows(df_gb, df_p) %>%
  mutate(country = case_when(Win == 1~"Kenya", TRUE~"Tanzania"))

df_winloss_plot %>%
  ungroup() %>%
  filter(name %in% c("natpride", "nateth", "afrpride", "nat_govspend_4_1")) %>%
  mutate(name = case_when(name == "natpride"~"National Pride",
                        name == "nateth"~"National vs. Ethnic",
                        name == "afrpride"~"African Pride",
                        name == "nat_govspend_4_1"~"Resources for Conationals",
                        TRUE~"ruh-roh"),
         name = fct_relevel(name, "National Pride", 
                                "National vs. Ethnic", 
                                "African Pride",
                                "Resources for Conationals")) %>%
  ggplot(aes(time_period, est, group = country, colour = country)) + 
  geom_point(alpha = .5) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lty = 1.2, alpha = .5) + 
  geom_smooth() + 
  geom_vline(xintercept = 4.5, lty = 2) +
  geom_vline(xintercept = 5.5, lty = 2) +
  geom_vline(xintercept = 6.5, lty = 2) +
  scale_colour_manual(values = c("red","blue")) + 
  facet_wrap(~name, nrow = 1, scales = "free_y") + 
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11),
          legend.position = 'bottom',
          axis.text.x = element_text(hjust=1, angle = 45, size=10))

@

<<3day_winloss_RefAtt, eval = TRUE, echo = FALSE, tidy=TRUE, fig.pos='H', fig.width = 10.5, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="All point estimates include 95$\\%$ CIs.">>=

# INCLUDE DASHED LINES WHEN THE GAMES ARE

df_winloss_threeday <- ACUP %>% filter(doublerand == 0 & SurvPrime == 0) %>%
  dplyr::select(StartDate_e, StartDate_b, Win, 
                  starts_with("nateth"),
                  starts_with("natpride"), 
                  starts_with("afrpride"), 
                  starts_with("nat_govspend_4_1"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"), starts_with("ref_disease_recode"),
                  starts_with("ref_econ"), 
                  starts_with("nat_govspend_3_1")) %>%
  pivot_longer(cols = c(starts_with("nateth"),
                  starts_with("natpride"), 
                  starts_with("afrpride"), 
                  starts_with("nat_govspend_4_1"),
                  starts_with("ref_crime_recode"),
                  starts_with("ref_diverse"), starts_with("ref_disease_recode"),
                  starts_with("ref_econ"), 
                  starts_with("nat_govspend_3_1"))) %>%
  mutate(name = str_sub(name, 1, -3))

## Daily comparison
df_gb <- df_winloss_threeday %>% 
  mutate(time_period = as.Date(StartDate_b)) %>%
  mutate(time_period = case_when(time_period %in% as.Date(c("2019-06-12", "2019-06-13", "2019-06-14"))~"6/12 - 6/14",
                                time_period %in% as.Date(c("2019-06-15", "2019-06-16", "2019-06-17"))~"6/15 - 6/17",
                                time_period %in% as.Date(c("2019-06-18", "2019-06-19", "2019-06-20"))~"6/18 - 6/20",
                                time_period %in% as.Date(c("2019-06-21", "2019-06-22", "2019-06-23"))~"6/21 - 6/23",
                                time_period %in% as.Date(c("2019-06-24", "2019-06-25", "2019-06-26"))~"6/24 - 6/26",
                                TRUE~"ruh-roh")) %>%
  drop_na() %>%
  group_by(time_period, Win, name) %>%
  summarize(est = mean(value),
            se = sqrt(var(value) / n()),
            n = n(),
            lower = est - se * qnorm(.975), 
            upper = est + se * qnorm(.975)) %>%
  filter(se != 0)

df_p <- df_winloss_threeday %>%
  mutate(time_period = as.Date(StartDate_e)) %>%
  mutate(time_period = case_when(time_period %in% as.Date(c("2019-06-27", "2019-06-28", "2019-06-29", "2019-06-30"))~"6/27 - 6/30",
                                time_period %in% as.Date(c("2019-07-01", "2019-07-02", "2019-07-03"))~"7/01 - 7/03",
                                time_period %in% as.Date(c("2019-07-04", "2019-07-05", "2019-07-06"))~"7/04 - 7/06",
                                time_period %in% as.Date(c("2019-07-07", "2019-07-08", "2019-07-09"))~"7/07 - 7/09",
                                time_period %in% as.Date(c("2019-07-10", "2019-07-11", "2019-07-12", "2019-07-13"))~"7/10 - 7/13",
                                TRUE~"ruh-roh")) %>%
  drop_na() %>%
  group_by(time_period, Win, name) %>%
  summarize(est = mean(value),
            se = sqrt(var(value) / n()),
            n = n(),
            lower = est - se * qnorm(.975), 
            upper = est + se * qnorm(.975)) %>%
  filter(se != 0)

df_winloss_plot <- bind_rows(df_gb, df_p) %>%
  mutate(country = case_when(Win == 1~"Kenya", TRUE~"Tanzania"))

df_winloss_plot %>%
  ungroup() %>%
  filter(name %in% c("ref_crime_recode", "ref_diverse", "ref_disease_recode", "ref_econ", "nat_govspend_3_1")) %>%
    mutate(name = case_when(name == "ref_crime_recode"~"Refugee Crime",
                        name == "ref_diverse"~"Refugee Diversity",
                        name == "ref_disease_recode"~"Refugee Disease",
                        name == "ref_econ"~"Refugee Economy",
                        name == "nat_govspend_3_1"~"Resources for Refugees",
                        TRUE~"ruh-roh"),
    name = fct_relevel(name, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy", "Resources for Refugees")) %>%
  ggplot(aes(time_period, est, group = country, colour = country)) + 
  geom_point(alpha = .5) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lty = 1.2, alpha = .5) + 
  geom_smooth() + 
  geom_vline(xintercept = 4.5, lty = 2) +
  geom_vline(xintercept = 5.5, lty = 2) +
  geom_vline(xintercept = 6.5, lty = 2) +
  scale_colour_manual(values = c("red","blue")) + 
  facet_wrap(~name, nrow = 1, scales = "free_y") + 
  theme(panel.background = element_blank(),
          legend.title = element_blank(), 
          plot.title = element_text(size = 10),
          panel.border = element_rect(colour = "gray50", fill=NA, size=.11),
          legend.position = 'bottom',
          axis.text.x = element_text(hjust=1, angle = 45, size=10))

@

Note that the difference between these plots and the pre- and post-match means shown in other figures is that these subset down to only the survey control group, i.e. did not receive any survey primes. 


%%% ROBUSTNESS CHECKS
\newpage
\section{Robustness Checks}
\subsection{Robustness Check using Clean Study Window}
\label{sec:cleanwindow}

In this section, we rerun the main analyses presented in Figures \ref{fig:Pride} and \ref{fig:RefAtt} using only the 6 day ``clean window,'' which occurs \textit{after} the June 23 match in which Tanzania lost to Senegal and Kenya lost to Algeria, and \textit{before} the July 1 match in which Kenya lost to Senegal and Tanzania lost to Algeria. 

%%% CLEAN WINDOW ANALYSES HERE

<<ModelFunctions_SI_clean, eval = TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, message=FALSE>>=

## Get main results - treatment effects
teff_df_sub <- run_mods(data = ACUP_sub %>% filter(doublerand == 0),
                        ctrl_formula = ~Win + female + age_numb2 + 
                          edu + urban + livedout + ref_know + job + hh_wealth + 
                          voted_last2 + polclose + religion2 + religiosity +
                          UserLanguage_b)

## Function to show pre/post change
prepost_df_sub <- ACUP_sub %>% filter(doublerand == 0) %>%
  dplyr::select(country,
         starts_with("idcircle_"),
         starts_with("nateth"),
         starts_with("natpride"),
         starts_with("ethpride"),
         starts_with("afrpride"),
         #starts_with("affective_1"),
         #starts_with("affective_2"),
         #starts_with("behavioral_1"),
         #starts_with("behavioral_2"),
         #starts_with("cognitive_1"),
         #starts_with("cognitive_2"),
         #starts_with("affective_std"),
         #starts_with("behavioral_std"),
         #starts_with("cognitive_std"),
         #starts_with("oth_eth"),
         #starts_with("oth_nonpartisan"),
         #starts_with("oth_noneth"),
         #starts_with("oth_rival"),
         #starts_with("oth_econmig"),
         #starts_with("oth_refugee"),
         starts_with("ref_crime_recode"),
         starts_with("ref_diverse"),
         starts_with("ref_disease_recode"),
         starts_with("ref_econ"),
         #starts_with("govcit_recode"),
         #starts_with("govbord_recode"),
         #starts_with("eamove"),
         starts_with("ref_post"),
         starts_with("nat_govspend_"),
         #starts_with("comm_coeth_premium"),
         #starts_with("comm_conat_premium"),
         #starts_with("comm_20eth_response"),
         #starts_with("comm_80eth_response"),
         #starts_with("comm_20nat_response"),
         #starts_with("comm_80nat_response")
         ) %>%
  dplyr::select(-contains("_DO_")) %>%
  gather(key = outcome, value = response, -c(country)) %>%
  drop_na() %>%
  mutate(time = case_when(str_sub(outcome, -2) == "_b"~"Pre",
                          str_sub(outcome, -2) == "_e"~"Post",
                          TRUE~"ruh-roh"),
         outcome = case_when(str_sub(outcome, -2) %in% c("_e", "_b")~str_sub(outcome, end=-3))) %>%
  group_by(country, time, outcome) %>%
  summarize(mean = mean(response),
            se = sd(response) / sqrt(n()),
            lower = mean - se * qnorm(.975),
            upper = mean + se * qnorm(.975)) %>%
  ungroup() %>% 
  mutate(time = fct_relevel(time, "Pre"))

## Function to show day-by-day estimates
df_byday_sub <- ACUP_sub %>% filter(doublerand == 0) %>%
  dplyr::select(country, 
         day_b, 
         day_e,
         starts_with("idcircle_"),
         starts_with("nateth"),
         starts_with("natpride"),
         starts_with("ethpride"),
         starts_with("afrpride"),
         #starts_with("affective_1"),
         #starts_with("affective_2"),
         #starts_with("behavioral_1"),
         #starts_with("behavioral_2"),
         #starts_with("cognitive_1"),
         #starts_with("cognitive_2"),   
         #starts_with("oth_eth"),
         #starts_with("oth_nonpartisan"),
         #starts_with("oth_noneth"),
         #starts_with("oth_rival"),
         #starts_with("oth_econmig"),
         #starts_with("oth_refugee"),
         starts_with("ref_crime_recode"),
         starts_with("ref_diverse"),
         starts_with("ref_disease_recode"),
         starts_with("ref_econ"),
         #starts_with("govcit_recode"),
         #starts_with("govbord_recode"),
         #starts_with("eamove"),
         starts_with("ref_post"),
         starts_with("nat_govspend_"),
         #starts_with("comm_20eth_response"),
         #starts_with("comm_80eth_response"),
         #starts_with("comm_20nat_response"),
         #starts_with("comm_80nat_response")
         ) %>%
  dplyr::select(-contains("_DO_")) 
df_baseline <- df_byday_sub %>% dplyr::select(country, ends_with("_b")) %>%
  rename_at(vars(ends_with("_b")), funs(str_replace(., "_b", "")))
df_endline <- df_byday_sub %>% dplyr::select(country, ends_with("_e")) %>%
  rename_at(vars(ends_with("_e")), funs(str_replace(., "_e", "")))

df_byday_sub <- bind_rows(df_baseline, df_endline) %>%
  gather(key = outcome, value = value, -c(country, day)) %>%
  drop_na() %>%
  group_by(country, day, outcome) %>%
  summarize(est = mean(value),
            se = sd(value) / sqrt(n()),
            lower = est - se * qnorm(.975),
            upper = est + se * qnorm(.975)) %>%
  ungroup() %>%
  mutate(day = as.Date(day))


@

<<Pride_sub, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 7, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure replicates Figure \\ref{fig:Pride} with the clean window.">>=

## Pride outcomes
prepost <- prepost_df_sub %>% filter(outcome %in% c("natpride", "nateth", "afrpride")) %>%
  ungroup() %>%
  mutate(
    outcome = case_when(outcome == "natpride"~"National Pride",
                        outcome == "nateth"~"National vs. Ethnic",
                        outcome == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
    outcome = fct_relevel(outcome, "National Pride", "National vs. Ethnic", "African Pride")
  ) %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lwd = 1.2) + 
  geom_line(lty = "dashed") + 
  facet_grid(~ outcome) +
  labs(x = "", y = "Average Response (5pt scale)") + 
  scale_colour_manual(values = c("red", "blue")) +
  scale_y_continuous(breaks = c(3, 4, 5), limits = c(3, 5)) + 
  yy_theme()

results <- teff_df_sub %>% filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "National Pride", "National vs. Ethnic", "African Pride"),
    term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size =.7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.3,0,.3), limits = c(-.5, .7)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend National
prepost2 <- prepost_df_sub %>% ungroup() %>%
  filter(grepl("nat_govspend_4_1", outcome)) %>%
  mutate(outcome = "Resources for Conationals") %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(lty = "dashed", position=position_dodge(width = .1)) + 
  annotate("text", x=2.3, y=2.5, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=2.36, label= "KY", color = "red") + 
  scale_y_continuous(breaks = c(2,2.5,3), limits = c(2, 3)) + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  yy_theme()

results2 <- teff_df_sub %>% ungroup() %>%
  filter(grepl("nat_govspend_4_1", response)) %>%
  mutate(response = "Resources for Conationals",
        term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size =.7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(limits = c(-1.2, 1.2)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(prepost + prepost2 + plot_layout(widths = c(3.5, 1))) / 
  (results + results2 + plot_layout(widths = c(3.5, 1))) 

@

The main effects of the win do not change with Figure \ref{fig:Pride_sub}. The one difference between the results presented in the paper and those presented here is that the effect of MatchInfo x Win loses statistical significance for National Pride. 

<<RefAtt_sub, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 7, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure replicates Figure \\ref{fig:RefAtt} with the clean window.">>=


## Attitude outcomes
prepost <- prepost_df_sub %>% filter(outcome %in% c("ref_crime_recode", 
                                                "ref_diverse",
                                                "ref_disease_recode", 
                                                "ref_econ")) %>%
  ungroup() %>%
  mutate(
    outcome = case_when(outcome == "ref_crime_recode"~"Refugee Crime",
                        outcome == "ref_diverse"~"Refugee Diversity",
                        outcome == "ref_disease_recode"~"Refugee Disease",
                        outcome == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    outcome = fct_relevel(outcome, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy")
  ) %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = lower, ymax = upper), width = 0, lwd = 1.2) + 
  geom_line(lty = "dashed") + 
  facet_grid(~ outcome) +
  labs(x = "", y = "Average Response (5pt scale)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  yy_theme()

results <- teff_df_sub %>% filter(response %in% c("ref_crime_recode", 
                                                "ref_diverse",
                                                "ref_disease_recode", 
                                                "ref_econ")) %>%
  ungroup() %>%
  mutate(
    response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),
    term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size =.7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend Refugee
prepost2 <- prepost_df_sub %>% ungroup() %>%
  filter(grepl("nat_govspend_3_1", outcome)) %>%
  mutate(outcome = "Resources for Refugees") %>%
  ggplot(aes(time, mean, group = country, colour = country)) + 
  geom_point(position=position_dodge(width = .1)) + 
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position=position_dodge(width = .1),
                width = 0, lwd = 1.2) + 
  geom_line(lty = "dashed", position=position_dodge(width = .1)) + 
  annotate("text", x=2.3, y=1.7, label= "TZ", color = "blue") + 
  annotate("text", x=2.3, y=1.8, label= "KY", color = "red") + 
  scale_y_continuous(limits = c(1.6, 2)) + 
  facet_wrap(~ outcome, nrow = 2) + 
  labs(x = "", y = "Average Resource Allocation (10 tokens)") + 
  scale_colour_manual(values = c("red", "blue")) + 
  yy_theme()

results2 <- teff_df_sub %>% ungroup() %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees",
         term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size =.7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.4,0,.4), limits = c(-.6, .8)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(prepost + prepost2 + plot_layout(widths = c(4, 1))) / 
  (results + results2 + plot_layout(widths = c(4, 1))) 

@

Figure \ref{fig:RefAtt_sub} illustrates that in this smaller window the effects of the survey primes lose statistical significance for Refugee Diversity and Resources for Refugees, but the positive direction of the estimates remain.  


\newpage
\subsection{Robustness Check adjusting for Attrition}
\label{sec:SIattrit}

In this section, we address concerns about endline attrition by rerunning the main analyses presented in Figures \ref{fig:Pride} and \ref{fig:RefAtt} and weighting the models by the inverse of the propensity of answering the endline survey \citep{Gerber:2012}. We first estimate a logit model predicting whether a respondent completes the endline survey, and then use the inverse of the predicted probabilities from that model as weights when reestimating our models. The intuition behind this method is that we upweight respondents who resemble those who attrited based on demographic covariates. It assumes that condition on these covariates, attrition is as-if random. Figures \ref{fig:Pride_ipw} and \ref{fig:RefAtt_ipw} show that results do not substantively change. 

<<balance_attrit, eval = FALSE, echo = FALSE, tidy=TRUE, fig.width = 8, fig.height = 4, fig.align='center', out.width= ".8\\linewidth", warning=FALSE, message=FALSE, fig.cap="This plot shows covariate imbalance comparing attritted respondents to non-attritted respondents.">>=

## Create indicator for attrittion
ACUP_base$attritted <- case_when(ACUP_base$uid %in% ACUP$uid2~0, TRUE~1)

## Create additional variables
ACUP_base$hh_wealth <- rowSums(ACUP_base[,c("hh_own_1","hh_own_2","hh_own_3",
                                            "hh_own_4","hh_own_5","hh_own_6","hh_own_7")],na.rm=T)

## Test for balance
baltest_out <- ACUP_base %>% 
  mutate(en_lan = case_when(UserLanguage_b == "EN"~1, TRUE~0),
         sw_lan = case_when(UserLanguage_b == "SW"~1, TRUE~0),
         female = case_when(sex == 1~1, TRUE~0),
         age_numb2 = case_when(age_numb > 100 ~ round(mean(age_numb[age_numb <= 100], 
                                                           na.rm = TRUE), 0), TRUE~age_numb), 
         voted_last2 = case_when(voted_last == 1~1, TRUE~0)) %>%
  dplyr::select(female, age_numb2, edu, urban, livedout, ref_know, job, hh_wealth,
         voted_last2, polclose, en_lan, sw_lan, attritted) %>%
  gather(key = var, value = outcome, -attritted) %>%
  group_by(var) %>%
  do({
    ## Run t-test of mean balance
    t_out <- try(t.test(outcome ~ attritted, data = .), silent = TRUE)
    data.frame(pval = t_out$p.value, 
               mean_group1 = t_out$estimate[1], mean_group2 = t_out$estimate[2])
  })

## Run KS test against uniform
ks_out <- data.frame(pval = ks.test(baltest_out$pval, "punif")$p.value) %>%
  mutate(pval = as.numeric(pval),
         text = paste0("KS Test P-value vs. Uniform: ", round(pval, 3)))

## Plot statistic
ggplot(baltest_out, aes(sample = pval)) + 
  stat_qq(distribution = stats::qunif) + 
  geom_text(data = ks_out, aes(x = .15, y = .95, label = text)) + 
  labs(x = "Theoretical Quantile", y = "Empirical Quantile") +
  yy_theme() +
  geom_abline(aes(intercept = 0, slope = 1), lty = "dashed")

## Report balance statistics
baltest_out %>% ungroup() %>%
  dplyr::select(var, mean_group1, mean_group2, pval) %>%
  rename(`Attritted Mean` = mean_group1, `Non-attritted Mean` = mean_group2) %>%
  mutate(`Attritted Mean` = round(`Attritted Mean`, 3),
         `Non-attritted Mean` = round(`Non-attritted Mean`, 3),
         pval = round(pval, 3)) %>%
  kable() %>%
  kable_styling(bootstrap_options = "striped")
@

<<Pride_ipw, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 4, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure replicates Figure \\ref{fig:Pride} using inverse propensity weights for attrition.">>=

## Create indicator for attrittion
ACUP_base$attritted <- case_when(ACUP_base$uid %in% ACUP$uid2~0, TRUE~1)
ACUP_base$attritted[ACUP_base$uid %in% ACUP$uid2[ACUP$doublerand == 1]] <- 1

## Create additional variables
ACUP_base$hh_wealth <- rowSums(ACUP_base[,c("hh_own_1","hh_own_2","hh_own_3",
                                            "hh_own_4","hh_own_5","hh_own_6","hh_own_7")],na.rm=T)

## Create IPW model
ACUP_base <- ACUP_base %>% 
  mutate(en_lan = case_when(UserLanguage_b == "EN"~1, TRUE~0),
         sw_lan = case_when(UserLanguage_b == "SW"~1, TRUE~0),
         female = case_when(sex == 1~1, TRUE~0),
         age_numb2 = case_when(age_numb > 100 ~ round(mean(age_numb[age_numb <= 100], 
                                                           na.rm = TRUE), 0), TRUE~age_numb), 
         voted_last2 = case_when(voted_last == 1~1, TRUE~0),
         observed = 1 - (attritted == 1))
pmod_out <- glm(observed ~ country*(female + age_numb2 + edu + urban + 
                  hh_wealth + voted_last2 + en_lan), data = ACUP_base,
                family = binomial(link = "logit"))

## Get IPW for weighting
ACUP$en_lan <- case_when(ACUP$UserLanguage_b == "EN"~1, TRUE~0)
ACUP$probobs <- predict(pmod_out, ACUP, "response")
ACUP$ipw <- 1 / ACUP$probobs

## ----------------------------
## Run the main models with IPW
## ----------------------------
cov_terms <- terms(~Win + female + age_numb2 + edu + urban + livedout + ref_know + 
                     job + hh_wealth + voted_last2 + polclose + religion2 + religiosity +
                     UserLanguage_b + Period)
## Analysis
teff_df <- ACUP %>% filter(doublerand == 0) %>% 
  dplyr::select(labels(cov_terms), MatchInfo, Diversity, PanAfrica, 
                SurvPrime, ipw, starts_with("idcircle_"), starts_with("nateth"),
                starts_with("natpride"), starts_with("ethpride"), starts_with("afrpride"),
                starts_with("ref_crime_recode"), starts_with("ref_diverse"),
                starts_with("ref_disease_recode"), starts_with("ref_econ"),
                starts_with("ref_post"), starts_with("nat_govspend_")) %>%
    dplyr::select(-contains("_DO_")) %>%
    mutate(respid = 1:n()) %>%
    gather(key = response, value = value, 
           -c(labels(cov_terms), MatchInfo, Diversity, PanAfrica, SurvPrime, ipw, respid)) %>% 
    mutate(time = case_when(str_ends(response, "_b")~"Baseline",
                            str_ends(response, "_e")~"Endline",
                            TRUE~"ruh-roh"),
           response = str_sub(response, 1, -3)) %>%
    group_by(response) %>%
    do({
      
      ## Marginalize over primes
      mod_base <- try(lm_robust(update(value ~ Win*time, reformulate(c(".",labels(cov_terms)))),
                           data = ., weights = ipw, clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>%
        filter(grepl("Win:timeEndline", term))
      
      ## Additional effect of each prime
      mod_inter <- try(lm_robust(update(value ~ MatchInfo*time*Win + 
                                          Diversity*time*Win + PanAfrica*time*Win, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., weights = ipw, clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>%
        filter(str_count(term, ":") == 2)
      
      ## Additional effect of any prime
      mod_anyprime <-  try(lm_robust(update(value ~ SurvPrime*time*Win, 
                                       reformulate(c(".", labels(cov_terms)))),
                           data = ., weights = ipw, clusters = respid
                           ), silent = TRUE) %>%
        tidy() %>% 
        filter(term == "SurvPrime:timeEndline:Win")
      
      ## Clean and output
      bind_rows(mod_base, mod_inter, mod_anyprime) %>%
        mutate(term = case_when(grepl("MatchInfo", term)~"MatchInfo x Win",
                                grepl("Diversity", term)~"Diversity x Win",
                                grepl("PanAfrica", term)~"PanAfrica x Win",
                                grepl("SurvPrime", term)~"Any Prime x Win",
                                TRUE~"Win"),
               term = fct_relevel(term, "Win"))
    }) 

## Pride outcomes
results <- teff_df %>% filter(response %in% c("natpride", "nateth", "afrpride")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        TRUE~"ruh-roh"),
  response = fct_relevel(response, "National Pride", 
                         "National vs. Ethnic", 
                         "African Pride"),
  term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win"),
  statsig = case_when(p.value < .05~"statsig", TRUE~"notstatsig")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = statsig, group = statsig)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  scale_colour_manual(values = c("black", "black")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.25,0,.25), limits = c(-.3, .5)) + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend National
results2 <- teff_df %>% ungroup() %>%
  filter(grepl("nat_govspend_4_1", response)) %>%
  mutate(response = "Resources for Conationals",
          term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win"),
  statsig = case_when(p.value < .05~"statsig", TRUE~"notstatsig")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate, colour = statsig, group = statsig)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  scale_colour_manual(values = c("black", "black")) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.4,0,.4), limits = c(-.6, .8)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(results + results2 + plot_layout(widths = c(3.5, 1))) 

@

<<RefAtt_ipw, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 10, fig.height = 4, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE, fig.cap="This figure replicates Figure \\ref{fig:RefAtt} using inverse propensity weights for attrition.">>=
## Attitude outcomes
results <- teff_df %>% filter(response %in% c("ref_crime_recode", 
                                                "ref_diverse",
                                                "ref_disease_recode", 
                                                "ref_econ")) %>%
  ungroup() %>%
  mutate(
    response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        TRUE~"ruh-roh"),
    response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", "Refugee Disease", "Refugee Economy"),
    term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  facet_grid(~ response) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme()

## Govspend Refugee
results2 <- teff_df %>% ungroup() %>%
  filter(grepl("nat_govspend_3_1", response)) %>%
  mutate(response = "Resources for Refugees",
          term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  ggplot(aes(x = reorder(term, desc(term)), y = estimate)) + 
  geom_point(size = 2) + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_y_continuous(breaks = c(-.4,0,.4), limits = c(-.6, .8)) + 
  facet_wrap(~ response, nrow = 2) + 
  labs(x = "Treatment", 
       y = "Average Treatment Effects") +
  coord_flip() +
  yy_theme() +
   theme(axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank())

## Plot
(results + results2 + plot_layout(widths = c(4, 1))) 
@


\newpage
\subsection{Placebo Tests}
\label{sec:SIplacebo}

The following placebo tests examine the effect of playing the first match on June 23, in which Tanzania lost to Senegal and Kenya lost to Algeria both by 2 - 0, to rule out the alternative explanation that simply playing a match in the Africa Cup would affect national pride or attitudes towards refugees. In these analyses, we must compare across respondents, those who responded to the baseline survey pre-June 23 versus those who responded to the baseline survey post-June 23 (subsetting out those who responded on June 23). We run the same OLS models, coding Kenya as having won even though both countries lost, without clustering at the respondent level (since the data set is no longer panel). We confirm there are no effects of the first game. 

<<placebo_firstgame, eval = TRUE, echo = FALSE, tidy=TRUE, fig.width = 8, fig.height = 5, fig.align='center', out.width= "1\\linewidth", warning=FALSE, message=FALSE>>=

ACUP_placebo <- ACUP %>% 
  mutate(StartDate_b = as.Date(StartDate_b),
         prepost_firstgame = case_when(StartDate_b < as.Date("2019/06/23")~"Before First Game", TRUE~"After First Game")) %>%
  filter(!(StartDate_b %in% as.Date(c("2019/06/23", "2019/06/27"))))

results_placebo <- ACUP_placebo %>%
  dplyr::select(natpride_b, nateth_b, afrpride_b, nat_govspend_4_1_b,
                ref_crime_recode_b, ref_diverse_b, ref_disease_recode_b,
                ref_econ_b, nat_govspend_3_1_b, prepost_firstgame, country,
                female, age_numb2, edu, urban, livedout, ref_know, job,
                hh_wealth, voted_last2, polclose, religion2, religiosity, 
                UserLanguage_b) %>%
  gather(key = response, value = value, 
         -c(prepost_firstgame, country, female, age_numb2, edu, urban, livedout, 
            ref_know, job, hh_wealth, voted_last2, polclose, religion2, religiosity, 
            UserLanguage_b)) %>%
  group_by(response) %>%
  do({
    mod_base <- lm_robust(value ~ country*prepost_firstgame + female + age_numb2 + 
                                             edu + urban + livedout + ref_know + 
                                             job + hh_wealth + voted_last2 + polclose + 
                                             religion2 + religiosity + UserLanguage_b,
                           data = .) %>%
        tidy() %>%
        filter(grepl(":prepost_firstgameBefore First Game", term))
    mod_base
  })

## Nationalism
natl_placeboplot <- results_placebo %>% filter(response %in% c("natpride_b", "nateth_b", 
                                           "afrpride_b", "nat_govspend_4_1_b")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "natpride_b"~"National Pride",
                              response == "nateth_b"~"National vs. Ethnic",
                              response == "afrpride_b"~"African Pride",
                              response == "nat_govspend_4_1_b"~"Resources for Conationals",
                              TRUE~"ruh-roh"),
          response = fct_relevel(response, "National Pride", "National vs. Ethnic", 
                                 "African Pride", "Resources for Conationals"))%>%
  ggplot(aes(response, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  ylim(-.4, .5) +
  yy_theme() + 
  labs(x = "Outcome", y = "Average Treatment Effects")

## Refugee attitudes
refatt_placeboplot <- results_placebo %>% filter(response %in% c("ref_crime_recode_b", "ref_diverse_b",
                         "ref_disease_recode_b", "ref_econ_b", "nat_govspend_3_1_b")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "ref_crime_recode_b"~"Refugee Crime",
                        response == "ref_diverse_b"~"Refugee Diversity",
                        response == "ref_disease_recode_b"~"Refugee Disease",
                        response == "ref_econ_b"~"Refugee Economy",
                        response == "nat_govspend_3_1_b"~"Resources for Refugees",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", 
                                "Refugee Disease", "Refugee Economy", 
                                "Resources for Refugees"))%>%
  ggplot(aes(response, estimate)) + 
  geom_point() + 
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high), width = .2, size = .7) + 
  geom_hline(aes(yintercept = 0), lty = "dashed", color = "gray30") + 
  scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) +
  ylim(-.4, .5) +
  yy_theme() + 
  labs(x = "Outcome", y = "Average Treatment Effects")

natl_placeboplot / refatt_placeboplot

@


%%% MULTIPLE HYPOTHESIS TESTING
\newpage
\section{Multiple Hypothesis Testing using Benjamini-Hochberg Procedure}
\label{sec:SImulthypothesis}

In this section, we address concerns about multiple hypothesis testing by adjusting for the false discovery rate (FDR). We show the Benjamini-Hochberg (BH) adjusted p-values for each test of our findings shown in Figures \ref{fig:Pride} and \ref{fig:RefAtt} in the paper. For the sets of outcomes, we show the adjusted p-values (1) within outcomes across estimates, and then (2) within estimates across outcomes. Most of our statistically significant findings hold, with the exception of National vs. Ethnic's effect of Win; Refugee Disease's effect of Diversity x Win; and Resources for Refugees' effect of Pan Africa x Win.

<<bh_adjustment_natl, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

## Nationalism outcomes BH
natl_outcomes <- teff_df %>% 
  filter(response %in% c("natpride", "nateth", "afrpride", "nat_govspend_4_1")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "natpride"~"National Pride",
                        response == "nateth"~"National vs. Ethnic",
                        response == "afrpride"~"African Pride",
                        response == "nat_govspend_4_1"~"Resources for Conationals",
                        TRUE~"ruh-roh"),
  response = fct_relevel(response, "National Pride", 
                         "National vs. Ethnic", 
                         "African Pride", "Resources for Conationals"),
  term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  arrange(response, term)

natl_outcomes %>% 
  group_by(response) %>%
  mutate(p.value.byoutcome.bh = p.adjust(p.value, method = "BH")) %>%
  inner_join(
    natl_outcomes %>% group_by(term) %>%
      mutate(p.value.bytreatment.bh = p.adjust(p.value, method = "BH"))
  ) %>%
  dplyr::select(term, response, estimate, std.error, p.value,
                p.value.byoutcome.bh, p.value.bytreatment.bh) %>%
  rename(Estimate = term, Outcome = response, `Effect Size` = estimate,
         SE = std.error, `p-value` = p.value, 
         `adj. p-value 1` = p.value.byoutcome.bh,
         `adj. p-value 2` = p.value.bytreatment.bh) %>%
  as.data.frame(row.names = FALSE) %>%
  xtable::xtable(
    caption = "Adjusted p-values using Benjamini-Hochberg for 
             Nationalism Analysis (Fig. \\ref{fig:Pride} in the paper)",
    align = c("l", "|l", "l", "l", "l", "l", "l", "l|")
  ) %>% 
  print(include.rownames = F, 
        scalebox = 1,
        table.placement="H",
        size="\\fontsize{9pt}{10pt}\\selectfont",
        hline.after = c(-1, 0, 5, 10, 15, 20))

@

<<bh_adjustment_ref, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

## Ref Att outcomes BH
ref_outcomes <- teff_df %>% 
  filter(response %in% c("ref_crime_recode", "ref_diverse",
                         "ref_disease_recode", "ref_econ", "nat_govspend_3_1")) %>%
  ungroup() %>%
  mutate(response = case_when(response == "ref_crime_recode"~"Refugee Crime",
                        response == "ref_diverse"~"Refugee Diversity",
                        response == "ref_disease_recode"~"Refugee Disease",
                        response == "ref_econ"~"Refugee Economy",
                        response == "nat_govspend_3_1"~"Resources for Refugees",
                        TRUE~"ruh-roh"),
         response = fct_relevel(response, "Refugee Diversity", "Refugee Crime", 
                                "Refugee Disease", "Refugee Economy", 
                                "Resources for Refugees"),
         term = fct_relevel(term, "Win", 
                         "Any Prime x Win", 
                         "MatchInfo x Win",
                         "Diversity x Win",
                         "PanAfrica x Win")) %>%
  arrange(response, term)

ref_outcomes %>% 
  group_by(response) %>%
  mutate(p.value.byoutcome.bh = p.adjust(p.value, method = "BH")) %>%
  inner_join(
    ref_outcomes %>% group_by(term) %>%
      mutate(p.value.bytreatment.bh = p.adjust(p.value, method = "BH"))
  ) %>%
  dplyr::select(term, response, estimate, std.error, p.value,
                p.value.byoutcome.bh, p.value.bytreatment.bh) %>%
  rename(Estimate = term, Outcome = response, `Effect Size` = estimate,
         SE = std.error, `p-value` = p.value, 
         `adj. p-value 1` = p.value.byoutcome.bh,
         `adj. p-value 2` = p.value.bytreatment.bh) %>%
  as.data.frame(row.names = FALSE) %>%
  xtable::xtable(
    caption = "Adjusted p-values using Benjamini-Hochberg for 
             Attitudes towards Refugees Analysis (Fig. \\ref{fig:RefAtt} in the paper)",
    align = c("l", "|l", "l", "l", "l", "l", "l", "l|")
  ) %>% 
  print(include.rownames = F, 
        scalebox = 1,
        table.placement="H",
        size="\\fontsize{9pt}{10pt}\\selectfont",
        hline.after = c(-1, 0, 5, 10, 15, 20, 25))

@


%%% REGRESSION TABLES 
\newpage
\section{Regression Tables}
\label{sec:SIregtables}


<<regtables_runmods, eval = TRUE, echo = FALSE, tidy=TRUE, warning=FALSE, message=FALSE, strip.white=TRUE>>=

ctrl_formula = ~Win + female + age_numb2 + edu + urban + livedout + ref_know + 
  job + hh_wealth + voted_last2 + polclose + religion2 + religiosity + UserLanguage_b + 
  Period

cov_terms <- terms(ctrl_formula)

## Create modeling df
est_df <- ACUP %>% filter(doublerand == 0) %>% 
  dplyr::select(labels(cov_terms), 
                  MatchInfo,
                  Diversity,
                  PanAfrica,
                  SurvPrime,
                  starts_with("natpride_"), 
                  starts_with("nateth_"), 
                  starts_with("afrpride_"), 
                  starts_with("nat_govspend_4_1_"),
                  starts_with("ref_crime_recode_"), 
                  starts_with("ref_diverse_"),
                  starts_with("ref_disease_recode_"), 
                  starts_with("ref_econ_"), 
                  starts_with("nat_govspend_3_1_")
                  ) %>%
    dplyr::select(-contains("_DO_")) %>%
    mutate(respid = 1:n()) %>%
    gather(key = response, value = value, 
           -c(labels(cov_terms), MatchInfo, Diversity, PanAfrica, SurvPrime,
              respid)) %>% 
    mutate(time = case_when(str_ends(response, "_b")~"Baseline",
                            str_ends(response, "_e")~"Endline",
                            TRUE~"ruh-roh"),
           response = str_sub(response, 1, -3))

# ## Run model
# mod_natpride_win <- lm_robust(update(value ~ Win*time, reformulate(c(".",labels(cov_terms)))),
#                               data = est_df %>% filter(response == "natpride"), clusters = respid)

## Get variable names
varnames <- unique(est_df$response)

registerDoMC(detectCores()-1)
allmods <- foreach(i = 1:length(varnames)) %dopar% {

  ## Subset df
  est_df_var <- est_df %>% filter(response == varnames[i])

  ## Marginalize over primes
  mod_base <- lm_robust(update(value ~ Win*time, reformulate(c(".",labels(cov_terms)))),
                           data = est_df_var, clusters = respid
                        )

  ## Additional effect of each prime
  mod_inter <- lm_robust(update(value ~ MatchInfo*time*Win + Diversity*time*Win +
                                      PanAfrica*time*Win, reformulate(c(".", labels(cov_terms)))),
                           data = est_df_var, clusters = respid
                         )

  ## Additional effect of any prime
  mod_anyprime <-  lm_robust(update(value ~ SurvPrime*time*Win,
                                       reformulate(c(".", labels(cov_terms)))),
                           data = est_df_var, clusters = respid
                           )

  ## Create output
  mods_out <- list(base = mod_base, anyprime = mod_anyprime, eachprime = mod_inter)
  return(mods_out)

}

names(allmods) <- varnames

@

<<regtable_pride_mod1, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$natpride$base, 
                  allmods$nateth$base,
                  allmods$afrpride$base,
                  allmods$nat_govspend_4_1$base),
          custom.model.names = c("National Pride M1", 
                          "National vs. Ethnic M1",
                          "African Pride M1",
                          "Resources for Conationals M1"),
          custom.coef.names=c("Intercept", 
                              "Win", 
                              "Post", 
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Win x Post"),
          reorder.coef=c(1, 2, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18),
          caption = "Regression table for Pride Outcomes Model 1 (effect of Win) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Pridetab_M1",
          scalebox='0.8',
          use.packages = FALSE,
          float.pos = "ht!"))

@

<<regtable_pride_mod2, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$natpride$anyprime, 
                  allmods$nateth$anyprime,
                  allmods$afrpride$anyprime,
                  allmods$nat_govspend_4_1$anyprime),
          custom.model.names = c("National Pride M2", 
                          "National vs. Ethnic M2",
                          "African Pride M2",
                          "Resources for Conationals M2"),
          custom.coef.names=c("Intercept", 
                              "Any Prime", 
                              "Post", 
                              "Win",
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Any Prime x Post",
                       "Win x Any Prime",
                       "Win x Post",
                       "Win x Any Prime x Post"),
          reorder.coef=c(1, 4, 2, 3, 21, 22, 20, 23, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
          caption = "Regression table for Pride Outcomes Model 2 (effect of Win x Any Prime) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Pridetab_M2",
          use.packages = FALSE,
          scalebox='0.8',
          float.pos = "H"))

@

<<regtable_pride_mod3, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$natpride$eachprime, 
                  allmods$nateth$eachprime,
                  allmods$afrpride$eachprime,
                  allmods$nat_govspend_4_1$eachprime),
          custom.model.names = c("National Pride M3", 
                          "National vs. Ethnic M3",
                          "African Pride M3",
                          "Resources for Conationals M3"),
          custom.coef.names=c("Intercept", 
                              "Match Info Prime", 
                              "Post", 
                              "Win",
                              "Diversity Prime",
                              "PanAfrica Prime",
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Match Info x Post",
                       "Win x Match Info",
                       "Win x Post",
                       "Diversity x Post",
                       "Win x Diversity",
                       "Pan Africa x Post",
                       "Win x PanAfrica",
                       "Win x Match Info x Post",
                       "Win x Diversity x Post",
                       "Win x PanAfrica x Post"),
          reorder.coef=c(1, 4, 2, 5, 6, 3, 23, 26, 28, 24, 22, 25, 27, 29, 30, 31,
                         7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21),
          caption = "Regression table for Pride Outcomes Model 3 (effects of Win x Match Info Prime,  
          Win x Diversity Prime, Win x PanAfrica Prime) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Pridetab_M3",
          scalebox='0.65',
          use.packages = FALSE,
          float.pos = "H"))

@

<<regtable_refatt_mod1, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$ref_diverse$base, 
                  allmods$ref_crime_recode$base,
                  allmods$ref_disease_recode$base,
                  allmods$ref_econ$base, 
                  allmods$nat_govspend_3_1$base),
          custom.model.names = c("Refugee Diversity M1", 
                          "Refugee Crime M1",
                          "Refugee Disease M1",
                          "Refugee Economy M1",
                          "Resources for Refugees M1"),
          custom.coef.names=c("Intercept", 
                              "Win", 
                              "Post", 
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Win x Post"),
          reorder.coef=c(1, 2, 3, 19, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18),
          caption = "Regression table for Refugee Attitudes Outcomes Model 1 (effect of Win) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Refatttab_M1",
          scalebox='0.75',
          use.packages = FALSE,
          float.pos = "H"))

@

<<regtable_refatt_mod2, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$ref_diverse$anyprime, 
                  allmods$ref_crime_recode$anyprime,
                  allmods$ref_disease_recode$anyprime,
                  allmods$ref_econ$anyprime, 
                  allmods$nat_govspend_3_1$anyprime),
          custom.model.names = c("Refugee Diversity M2", 
                          "Refugee Crime M2",
                          "Refugee Disease M2",
                          "Refugee Economy M2",
                          "Resources for Refugees M2"),
          custom.coef.names=c("Intercept", 
                              "Any Prime", 
                              "Post", 
                              "Win",
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Any Prime x Post",
                       "Win x Any Prime",
                       "Win x Post",
                       "Win x Any Prime x Post"),
          reorder.coef=c(1, 4, 2, 3, 21, 22, 20, 23, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
          caption = "Regression table for Refugee Attitudes Outcomes Model 2 (effect of Win x Any Prime) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Refatttab_M2",
          scalebox='0.7',
          use.packages = FALSE,
          float.pos = "H"))

@

<<regtable_refatt_mod3, echo = FALSE, tidy=TRUE, eval = TRUE, warning=FALSE, message=FALSE, strip.white=TRUE, results = "asis">>=

print(texreg(list(allmods$ref_diverse$eachprime, 
                  allmods$ref_crime_recode$eachprime,
                  allmods$ref_disease_recode$eachprime,
                  allmods$ref_econ$eachprime, 
                  allmods$nat_govspend_3_1$eachprime),
          custom.model.names = c("Refugee Diversity M3", 
                          "Refugee Crime M3",
                          "Refugee Disease M3",
                          "Refugee Economy M3",
                          "Resources for Refugees M3"),
          custom.coef.names=c("Intercept", 
                              "Match Info Prime", 
                              "Post", 
                              "Win",
                              "Diversity Prime",
                              "PanAfrica Prime",
                       "Female", 
                       "Age",
                       "Education Level",
                       "Urban", 
                       "Lived Out Length", 
                       "Knows Refugee", 
                       "Employment",
                       "Household Wealth", 
                       "Voted",
                       "Political",
                       "Religion Muslim",
                       "Religion Other",
                       "Religiosity",
                       "Language Swahili",
                       "Period Green-Pink",
                       "Match Info x Post",
                       "Win x Match Info",
                       "Win x Post",
                       "Diversity x Post",
                       "Win x Diversity",
                       "Pan Africa x Post",
                       "Win x PanAfrica",
                       "Win x Match Info x Post",
                       "Win x Diversity x Post",
                       "Win x PanAfrica x Post"),
          reorder.coef=c(1, 4, 2, 5, 6, 3, 23, 26, 28, 24, 22, 25, 27, 29, 30, 31,
                         7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21),
          caption = "Regression table for Refugee Attitudes Outcomes Model 3 (effects of Win x Match Info Prime,  
          Win x Diversity Prime, Win x PanAfrica Prime) using 
          OLS models with demographic covariates and respondent robust standard errors.",
          label = "tab:Refatttab_M3",
          scalebox='0.65',
          use.packages = FALSE,
          float.pos = "H"))

@


%%% REFERENCES
\newpage
\doublespace
\bibliography{africacup}

\end{document}
